<?php

/**
 * Reverse bidding system Buyer Class
 *
 * Buyer related functions are handled by this controller.
 *
 * @package        Reverse bidding system
 * @subpackage    Controllers
 * @category    Buyer
 * @author        Cogzidel Dev Team
 * @version        Version 1.0
 * @created        December 31 2008
 * @link        http://www.cogzidel.com
 *
 * <Reverse bidding system>
 * Copyright (C) <2009>  <Cogzidel Technologies>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 * If you want more information, please email me at bala.k@cogzidel.com or
 * contact us from http://www.cogzidel.com/contact
 */
class Buyer extends Controller
{

    //Global variable
    public $outputData; //Holds the output data for each view
    public $loggedInUser;

    /**
     * Constructor
     *
     * Loads language files and models needed for this controller
     */
    function Buyer()
    {
        parent::Controller();

        //Get Config Details From Db
        $this->config->db_config_fetch();


        //Manage site Status
        if ($this->config->item('site_status') == 1)
            redirect('offline');


        //Debug Tool
        //$this->output->enable_profiler=true;

        //Load Models Common to all the functions in this controller
        $this->load->model('common_model');
        $this->load->model('user_model');
        $this->load->model('skills_model');
        $this->load->model('page_model');
        $this->load->model('email_model');
        $this->load->model('certificate_model');

        //Page Title and Meta Tags
        $this->outputData = $this->common_model->getPageTitleAndMetaData();

        //Get Logged In user
        $this->loggedInUser = $this->common_model->getLoggedInUser();
        $this->outputData['loggedInUser'] = $this->loggedInUser;

        //Get Footer content
        $conditions = array('page.is_active' => 1);
        $this->outputData['pages'] = $this->page_model->getPages($conditions);

        //Get Latest Projects
        $limit_latest = $this->config->item('latest_projects_limit');
        $limit3 = array($limit_latest);
        $this->outputData['latestProjects'] = $this->skills_model->getLatestProjects($limit3);

        //language file
        $this->lang->load('enduser/common', $this->config->item('language_code'));

        $this->outputData['current_page'] = 'buyer';

        //Load helpers
        $this->load->helper('users');
        $this->load->helper('file');

    } //Controller End
    // --------------------------------------------------------------------


    /**
     * Loads the top buyers.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function getBuyersreview()
    {
        //language file
        $this->lang->load('enduser/review', $this->config->item('language_code'));

        //Load the top buyers
        $this->outputData['topBuyers'] = $this->skills_model->getTopBuyers();

        $this->outputData['getUsers'] = $this->user_model->getUsers();


        $this->load->view('buyer/topBuyer', $this->outputData);

    } //End of top buyers review

    /**
     * Loads Buyer signUp page.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function signUp()
    {

        if($this->session->userdata('user_id'))
             redirect('home');
        //language file

        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('skills_model');
        $this->load->model('email_model');
        //load validation libraray

        $this->load->library('form_validation');
        $this->load->library('log_balance');

        //Load Form Helper
        $this->load->helper('form');


        $this->load->helper('alert');
        $this->load->helper('transaction');



		
		$userGG = $this->session->userdata('userGG');
		if($userGG != FALSE){
			$this->outputData['userGG'] = $userGG;
			//$this->session->unset_userdata('userGG');		
		}
		
        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));
        //Get Form Data

        if ($this->input->post('buyerConfirm')) {

            //Set rules
            $this->form_validation->set_rules('username', 'lang:buyer_name_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|callback__check_username|alpha_space|is_unique[users.user_name]');
            $this->form_validation->set_rules('password', 'lang:password', 'required|trim|min_length[5]|max_length[50]|xss_clean');
            $this->form_validation->set_rules('confirm-password', 'lang:password_confirm_validation', 'required|trim|min_length[5]|max_length[50]|xss_clean|matches[password]');
            $this->form_validation->set_rules('email', 'lang:email', 'required|trim|required|valid_email|min_length[5]|max_length[50]|xss_clean|callback__check_buyer_email|alpha_space|[users.email]');
            $this->form_validation->set_rules('role_id',"lang:I'm looking for",'required');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
            $this->form_validation->set_message('max_length', '%s ' . $this->lang->line('max_length'));
            $this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));
            $this->form_validation->set_message('matches', '%s ' . $this->lang->line('matches'));
            $this->form_validation->set_message('is_unique', '%s ' . $this->lang->line('is_unique'));

            if ($this->form_validation->run() == TRUE) {

                // if (check_form_token() === false) {
                //     $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('token_error')));
                //     redirect('home');
                // }

//                if($this->input->post('avatar-facebook',TRUE) != ""){
//                    //var_dump(url_download(,));
//                    $filename = $this->input->post('username',TRUE).".jpg";
//                    @file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents($this->input->post('avatar-facebook',TRUE)));
//                }else{
//                    $filename = "";
//                }


                $data = array();
                $data['user_name'] = $this->input->post('username', TRUE);
                $data['password'] = md5($this->input->post('password', TRUE));
                $data['email'] = $this->input->post('email', TRUE);
                $data['user_status'] = 1;
                $data['role_id'] = $this->input->post('role_id');
                //$data['logo'] = $filename;

                // create User into database
                if($this->user_model->createUser($data) == TRUE ){
                    $conditions = array('user_name' => $this->input->post('username', TRUE), 'password' => md5($this->input->post('password', TRUE)), 'users.user_status' => '1');
                    $query = $this->user_model->getUsers($conditions);
                    if ($query->num_rows() > 0) {

                        $row = $query->row();
                        // update the last activity in the users table
                        $updateData = array();
                        $updateData['last_activity'] = get_est_time();

                        if($this->session->userdata('infoFacebook')){
                            $infoFacebook = $this->session->userdata('infoFacebook');
                            
                            $insertFacebook['facebook_id'] = $infoFacebook['id'];
                            $insertFacebook['link'] = $infoFacebook['link'];
                            $insertFacebook['locale'] = $infoFacebook['locale'];
                            $insertFacebook['name'] = $infoFacebook['name'];
                            $insertFacebook['verified'] = $infoFacebook['verified'];
                            $insertFacebook['created'] = time();
                            $insertFacebook['user_id'] = $row->id;

                            $this->user_model->addUserFacebook($insertFacebook);


                            // cộng điểm kinh nghiệm
                            creditExperience($row->id,10);
                            // cộng điểm thưởng
                            creditBonus($row->id,5);

                            $filename = md5(rand()).".jpg";
                            @file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents("https://graph.facebook.com/{$insertFacebook['facebook_id']}/picture?type=large"));
                            $updateData['logo'] = $filename;
                            $this->session->unset_userdata('infoFacebook');
                        }

						//update thong tin g+
						$userGG = $this->session->userdata('userGG');
						
						if($userGG !== FALSE){
							$this->load->model('user_google_model');
							$insertUserGG = array(
								'user_id' => $row->id,
								'google_id' => $userGG['id'],
								'display_name' => $userGG['displayName'],
								'gender' => $userGG['gender'],
								'avartar' => $userGG['image']['url'],
								'birthday' => isset($userGG['birthday'])?$userGG['birthday']:'',
								'created' => time()
							);
							$this->user_google_model->addUserGoogle($insertUserGG);
							
							$filename = md5(rand()).".jpg";
							@file_put_contents($this->config->item('basepath')."files/logos/".$filename, file_get_contents($userGG['picture']));
							$updateData['logo'] = $filename;
							
							// cộng điểm kinh nghiệm
							creditExperience($row->id,10);
							// cộng điểm thưởng
							creditBonus($row->id,5);
						}
						
						
                        // update process for users table
                        $this->user_model->updateUser(array('id' => $row->id), $updateData);
                        if (1) {
                            //Set Session For User
                            $this->auth_model->setUserSession($row);
                            /*echo "<pre>";
                            print_r($this->loggedInUser);
                            echo "</pre>";*/

                            // tạo biến random và update vào csdl
                            $rand_temp = md5(uniqid(time(),TRUE));
                            // update vào csdl
                            $conditionUpdate = array("users.email" => $this->input->post("email",TRUE));
                            $updateData = array("users.active_email" => $rand_temp);
                            $this->user_model->updateKeyRand($conditionUpdate,$updateData);

                            // gửi email yêu cầu users confirm
                            if($this->input->post("role_id",TRUE) == 1){
                                // kiểm tra vai trò người dùng để lựa chọn cấu trúc gửi mail
                                $conditionUserMail = array('email_templates.type' => 'buyers_signup');
                                $splVars = array(
                                    "!site_name" => site_url(''),
                                    "!activation_url" => site_url('users/active_mail_register/'.$rand_temp),
                                    "!contact_url" => "Appota Sai Gon",
                                );
                                $splVars1 = array("!site_name" => site_url(''));
                            }else{
                                $conditionUserMail = array('email_templates.type' => 'programmers_signup');
                                $splVars = array(
                                    "!site_title" => $this->config->item('site_title'),
                                    "!activation_url" => site_url('users/active_mail_register/'.$rand_temp),
                                    "!contact_url" => "Appota Sai Gon",
                                );
                                $splVars1 = array("!site_title" => $this->config->item('site_title'));
                            }

                            $result = $this->email_model->getEmailSettings($conditionUserMail);
                            $rowUserMailContent = $result->row();

                            $mailSubject = strtr($rowUserMailContent->mail_subject, $splVars1);
                            $mailContent = strtr($rowUserMailContent->mail_body, $splVars);
                            $toEmail = $this->input->post("email",TRUE);
                            $fromEmail = $this->config->item('site_admin_mail');

                            // send Email
                            $result_send = $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                            if($result_send){
                                //send mail success
                                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', 'Your password has been sent to your registered email address!'));
                            }else{
                                //send mail failed
                                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Send Email failed'));
                            }

                            // Chuyển đến trang cụ thể tùy theo Buyer hoặc developer
                            if($row->role_id == 1){

                                // cộng điểm kinh nghiệm
                                creditExperience($row->id,10);
                                
                                // cộng điểm thưởng
                                creditBonus($row->id,5);
                                // nếu giá trị buyerConfirm != buyerConfirm  thì chuyển về trang viewFreelancerWhenUnregister
                                if($this->input->post('buyerConfirm') != 'buyerConfirm')
                                    redirect($this->input->post('buyerConfirm'));

                                // chuyển đến trang đăng dự án
                                $projectId = $this->uri->segment(3,'0');
                                if(!empty($projectId) && is_numeric($this->uri->segment(3,'0')) && $this->uri->segment(3,'0') != 0)
                                    redirect('project/create/'.$this->uri->segment(3,'0'));
                                else
                                    redirect('project/create');
                            }elseif($row->role_id == 2){

                                // cộng điểm kinh nghiệm
                                creditExperience($row->id,10);

                                // cộng điểm thưởng
                                creditBonus($row->id,5);
                                
                                // chuyển đến trang profile setting
                                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('buyer_confirm_success')));
                                redirect('buyer/editProfileUpdate');
                            }
                        }
                    }
                    //$expire = 60 * 60 * 24 * 100;
                    //$this->auth_model->setUserCookie('user_name',$this->input->post('username',TRUE),$expire);
                    //$this->auth_model->setUserCookie('user_password',md5($this->input->post('password',TRUE)),$expire);
                    //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('buyer_confirm_success')));
                    //redirect('users/login');
                }

                //$this->session->unset_userdata('refId');


                //Notification message

            }//Form Validation End
			

        } //If - Form Submission End


        $this->load->view('buyer/buyerSignup', $this->outputData);

    } //Function signUp End

    // --------------------------------------------------------------------

    /**
     * Resending activation link
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function resendActLink()
    {
        //language file
        $this->lang->load('enduser/buyerSignup', $this->config->item('language_code'));

        //load validation library
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        //Get Form Data
        if ($this->input->post('resend', TRUE)) {
            //Set rules
            $this->form_validation->set_rules('email2', 'lang:buyer_email_validation', 'required|trim|valid_email|xss_clean|callback__check_resendbuyer_email');

            if ($this->form_validation->run()) {
                $email = $this->input->post('email2', TRUE);
                //Conditions
                $conditions = array('users.email' => $email, 'users.role_id' => $this->user_model->getRoleId('buyer'));
                $query = $this->user_model->getUsers($conditions);
                $userRow = $query->row();

                //Load Model For Mail
                $this->load->model('email_model');
                
                //Send Mail
                $conditionUserMail = array('email_templates.type' => 'buyers_signup');
                $result = $this->email_model->getEmailSettings($conditionUserMail);

                $rowUserMailConent = $result->row();

                $splVars = array("!site_name" => $this->config->item('site_title'), "!activation_url" => site_url('buyer/confirm/' . $userRow->activation_key), "!contact_url" => site_url('contact'));
                $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                $toEmail = $email;
                $fromEmail = $this->config->item('site_admin_mail');
                $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

                //Set the Success Message
                $success_msg = $this->lang->line('confirmation_text') . $userRow->email . $this->lang->line('follow_the_link');

                //Notification message
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $success_msg));
                redirect('buyer/signUp');
            }
        }
        $this->load->view('buyer/buyerSignup', $this->outputData);
    }

    // --------------------------------------------------------------------

    /**
     * Loads confirm page for buyer
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function test()
    {
        if ($this->input->post('submit')) {
            try {
                print_r($this->input->post());
                exit;
            } catch (Exception $e) {
                echo $e->getMessage();
                exit;
            }
        }
        $this->load->view('buyer/test');
    }

    function confirm()
    {
        //language file
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        //Load Models - for this function
        $this->load->model('skills_model');

        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        //Get Form Data
        if ($this->input->post('buyerConfirm')) {
            var_dump($this->input->post());
            exit;
            //Set rules
            $this->form_validation->set_rules('username', 'lang:buyer_name_validation', 'required|trim|min_length[5]|max_length[20]|xss_clean|callback__check_username|alpha_space');
            $this->form_validation->set_rules('password', 'lang:password', 'required|trim|min_length[5]|max_length[20]|xss_clean');
            $this->form_validation->set_rules('confirm-password', 'lang:password_confirm_validation', 'required|trim|min_length[5]|max_length[20]|xss_clean|matches[password]');
            $this->form_validation->set_rules('email', 'lang:email', 'required|trim|required|valid_email|min_length[5]|max_length[20]|xss_clean|callback__check_buyer_email|alpha_space');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
            $this->form_validation->set_message('max_length', '%s ' . $this->lang->line('max_length'));
            $this->form_validation->set_message('valid_email', '%s ' . $this->lang->line('valid_email'));
            $this->form_validation->set_message('matches', '%s ' . $this->lang->line('matches'));

            //$this->form_validation->set_rules('name','lang:name_validation','trim|min_length[5]|xss_clean');
            //$this->form_validation->set_rules('logo','lang:logo_validation','callback__logo_check');
            //$this->form_validation->set_rules('country','lang:country_validation','required|xss_clean');
            //$this->form_validation->set_rules('state','lang:state_validation','trim|xss_clean');
            //$this->form_validation->set_rules('city','lang:city_validation','trim|xss_clean');
            //$this->form_validation->set_rules('signup_agree_terms','lang:signup_agree_terms_validation','required');
            //$this->form_validation->set_rules('signup_agree_contact','lang:signup_agree_contact_validation','required');
            //$this->form_validation->set_rules('confirmKey','Confirmation Key','callback__check_activation_key');
            //$this->form_validation->set_rules('msn','msn','trim|xss_clean');
            //$this->form_validation->set_rules('gtalk','gtalk','trim|xss_clean');
            //$this->form_validation->set_rules('yahoo','yahoo','trim|xss_clean');
            //$this->form_validation->set_rules('skype','skype','trim|xss_clean');


            if ($this->form_validation->run() == TRUE) {
//                if (check_form_token() === false) {
//                    $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('token_error')));
//                    redirect('info');
//                }

                $data = array();


                $updateData['user_status'] = '1';


                if ((isset($this->outputData['file']))) {

                    $updateData['logo'] = $this->outputData['file']['file_name'];
                    $thumb1 = $this->outputData['file']['file_path'] . $this->outputData['file']['raw_name'] . "_thumb" . $this->outputData['file']['file_ext'];
                    GenerateThumbFile($this->outputData['file']['full_path'], $thumb1, 49, 48);
                }


                //Create User
                $updateKey = array('activation_key' => $this->input->post('confirmKey', TRUE));
                // print_r($updateData);
                $this->user_model->updateUser($updateKey, $updateData);

                $this->session->unset_userdata('refId');


                $user = $this->user_model->getUsers($updateKey);
                $userDetails = $user->row();

                $contacts = array();
                $contacts['msn'] = $this->input->post('contact_msn', TRUE);
                $contacts['gtalk'] = $this->input->post('contact_gtalk', TRUE);
                $contacts['yahoo'] = $this->input->post('contact_yahoo', TRUE);
                $contacts['skype'] = $this->input->post('contact_skype', TRUE);
                $contacts['user_id'] = $userDetails->id;
                $this->user_model->insertUserContacts($contacts);

                if (count($userDetails) > 0) {
                    //Get the last insert username
                    $condition = array('users.activation_key' => $this->uri->segment(3));
                    $registerusers = $this->user_model->getUsers($condition);

                    $registerusers = $registerusers->row();
                    //Send email to the user after registration
                    $conditionUserMail = array('email_templates.type' => 'registration');
                    $result = $this->email_model->getEmailSettings($conditionUserMail);

                    $rowUserMailConent = $result->row();

                    $splVars = array("!site_name" => $this->config->item('site_title'), "!username" => $updateData['user_name'], "!password" => $this->input->post('password'), "!usertype" => 'Buyer', "!siteurl" => site_url(), "!contact_url" => site_url('contact'));
                    $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                    $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                    $toEmail = $registerusers->email;
                    $fromEmail = $this->config->item('site_admin_mail');
                    $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                    $insertData = array();
                    $insertData['username'] = $this->input->post('username');
                    $insertData['password'] = md5($this->input->post('password'));
                    $expire = 60 * 60 * 24 * 100;
                    $this->auth_model->setUserCookie('user_name', $insertData['username'], $expire);
                    $this->auth_model->setUserCookie('user_password', $insertData['password'], $expire);
                    redirect('users/login');
                }

                //Notification message
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('buyer_confirm_success')));
                redirect('info/index/success');
            } //Form Validation End


        } //If - Form Submission End

        //Get Countries
        $this->outputData['countries'] = $this->common_model->getCountries();

//		//Get Activation Key
//		$activation_key = $this->uri->segment(3,'0');
//
//		//Conditions
//		$conditions		= array('users.role_id' => '1','users.activation_key'=>$activation_key);
//
//		$query 			= $this->user_model->getUsers($conditions);
//
//		if($query->num_rows==1)
//		{
//			$row = $query->row();
//		} else { echo 123;exit;
//			$this->session->set_flashdata('flash_message', $this->common_model->flash_message('error',$this->lang->line('buyer_activationkey_error')));
//			redirect('info');
//		}

        //Puhal changes To get the Privacy Policy Contents
        $like = array('page.url' => '%privacy%');
        $this->outputData['page_content'] = $this->page_model->getPages(NULL, $like, NULL);

        //Puhal Chnages To get the company and conditions Contents

        $like = array('page.url' => '%ter%');
        $like1 = array('page.url' => '%cond%');
        $this->outputData['page_content1'] = $this->page_model->getPages(NULL, $like, $like1);

        //$this->outputData['confirmed_mail']	= $row->email;

        $this->load->view('buyer/buyerConfirm', $this->outputData);

    }//Function confirm End

    // --------------------------------------------------------------------

    /**
     * editProfile for both buyer and programmer for edit his profile
     *
     * @access    public
     * @param    nil
     * @return    void
     */

    function editProfile()
    {

        //language file
        $this->lang->load('enduser/editProfile', $this->config->item('language_code'));



        //Check Whether User Logged In Or Not
        if (!isset($this->loggedInUser->id)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be login access to this page')));
            redirect('info');
        }


        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        if ($this->input->post('updateBuyerProfile', TRUE)) {
            //Set rules
            $this->form_validation->set_rules('logo', 'lang:logo_validation', 'callback__logo_check');
            $this->form_validation->set_rules('name', 'lang:programmer_name_validation', 'required|trim|min_length[5]|xss_clean');
            $this->form_validation->set_rules('email', 'Email', 'required|trim|min_length[5]|xss_clean');
            if ($this->form_validation->run()) {
                $updateData = array();
                if ($this->input->post('pwd', TRUE) != '') {
                    $updateData['password'] = md5($this->input->post('pwd', TRUE));
                }
                $updateData['name'] = $this->input->post('name', TRUE);
                $updateData['email'] = $this->input->post('email', TRUE);
                $updateData['profile_desc'] = $this->input->post('profile', TRUE);
                $updateData['project_notify'] = $this->input->post('notify_project', TRUE);
                $updateData['message_notify'] = $this->input->post('notify_message', TRUE);
                //echo $this->loggedInUser->logo;exit;
                if (($this->loggedInUser->logo != '') and (isset($this->outputData['file']['file_name']))) {
                    $filepath = $this->config->item('basepath') . 'files/logos/' . $this->loggedInUser->logo;
                    //pr($this->outputData['file']);exit;
                    @unlink($filepath);
                    if (isset($this->outputData['file']['file_name'])) {

                        $updateData['logo'] = $this->outputData['file']['file_name'];

                        $thumb1 = $this->outputData['file']['file_path'] . $this->outputData['file']['raw_name'] . "_thumb" . $this->outputData['file']['file_ext'];

                        GenerateThumbFile($this->outputData['file']['full_path'], $thumb1, 49, 48);
                    }
                } else {

                    if (isset($this->outputData['file']['file_name'])) {
                        $updateData['logo'] = $this->outputData['file']['file_name'];
                        $thumb1 = $this->outputData['file']['file_path'] . $this->outputData['file']['raw_name'] . "_thumb" . $this->outputData['file']['file_ext'];
                        GenerateThumbFile($this->outputData['file']['full_path'], $thumb1, 49, 48);
                    }
                }

                $updateData['country_symbol'] = $this->input->post('country', TRUE);
                $updateData['state'] = $this->input->post('state', TRUE);
                $updateData['city'] = $this->input->post('city', TRUE);

                //Create User
                $updateKey = array('id' => $this->loggedInUser->id);
                $this->user_model->updateUser($updateKey, $updateData);

                $updateKey1 = array('users.activation_key' => $this->input->post('confirmKey'));
                $query = $this->user_model->getUsers($updateKey1);
                $row = $query->row();
                $userid = $row->id;
                $updateKey2 = array('user_contacts.user_id' => $this->loggedInUser->id);
                $query2 = $this->user_model->getUserContacts($updateKey2);
                $userDetails = $query2->row();

                if ($query2->num_rows() == 0) {
                    $insertData = array();
                    $insertData['user_id'] = $this->loggedInUser->id;
                    $insertData['msn'] = $this->input->post('contact_msn', TRUE);
                    $insertData['gtalk'] = $this->input->post('contact_gtalk', TRUE);
                    $insertData['yahoo'] = $this->input->post('contact_yahoo', TRUE);
                    $insertData['skype'] = $this->input->post('contact_skype', TRUE);

                    $this->user_model->insertUserContacts($insertData);
                } else {
                    //update data's in userContacts table
                    $userContacts['msn'] = $this->input->post('contact_msn', TRUE);
                    $userContacts['gtalk'] = $this->input->post('contact_gtalk', TRUE);
                    $userContacts['yahoo'] = $this->input->post('contact_yahoo', TRUE);
                    $userContacts['skype'] = $this->input->post('contact_skype', TRUE);

                    // update process for Content
                    $this->user_model->updateUserContacts($userContacts, $updateKey2);
                }
                //Send email to the buyer with the update profile details
                if ($this->input->post('pwd', TRUE))
                    $data1 = 'Password :' . $this->input->post('pwd') . '\n';
                else
                    $data1 = '';

                if ($this->input->post('name', TRUE))
                    $data2 = 'Company Name :' . $this->input->post('name', TRUE) . '\n';
                else
                    $data2 = '';

                if ($this->input->post('email', TRUE))
                    $data3 = 'Email Id :' . $this->input->post('email') . '\n';
                else
                    $data3 = '';

                if ($this->input->post('profile', TRUE))
                    $data4 = 'Profile Description :' . $this->input->post('profile') . '\n';
                else
                    $data4 = '';

                if ($this->input->post('notify_project', TRUE))
                    $data5 = 'Project Notify :' . $this->input->post('notify_project') . '\n';
                else
                    $data5 = '';

                if ($this->input->post('notify_message', TRUE))
                    $data6 = 'Message Notify :' . $this->input->post('notify_message') . '\n';
                else
                    $data6 = '';

                if ($this->input->post('country', TRUE)) {
                    $condition = array('country.country_symbol' => $this->input->post('country'));
                    $country = $this->common_model->getCountries($condition);
                    $country = $country->row();
                    $data7 = 'Country             :' . $country->country_name . '\n';
                } else
                    $data7 = '';

                if ($this->input->post('city', TRUE))
                    $data8 = 'City :' . $this->input->post('city') . '\n';
                else
                    $data8 = '';

                if ($this->input->post('state', TRUE))
                    $data9 = 'State :' . $this->input->post('state') . '\n';
                else
                    $data9 = '';

                if ($this->input->post('contact_msn', TRUE))
                    $data10 = 'MSN ID :' . $this->input->post('contact_msn') . '\n';
                else
                    $data10 = '';

                if ($this->input->post('contact_gtalk', TRUE))
                    $data11 = 'Gtalk ID :' . $this->input->post('contact_gtalk') . '\n';
                else
                    $data11 = '';

                if ($this->input->post('contact_yahoo', TRUE))
                    $data12 = 'Yahoo Id :' . $this->input->post('contact_yahoo') . '\n';
                else
                    $data12 = '';

                if ($this->input->post('contact_skype', TRUE))
                    $data12 = 'Skype Id :' . $this->input->post('contact_skype') . '\n';
                else
                    $data12 = '';

                //Send email to the user after update profile
                $conditionUserMail = array('email_templates.type' => 'profile_update');
                $result = $this->email_model->getEmailSettings($conditionUserMail);
                $rowUserMailConent = $result->row();

                $splVars = array("!site_name" => $this->config->item('site_title'), "!username" => $this->loggedInUser->user_name, "!siteurl" => site_url(), "!contact_url" => site_url('contact'), "!data1" => $data1, "!data2" => $data2, "!data3" => $data3, "!data4" => $data4, "!data5" => $data5, "!data6" => $data6, "!data7" => $data7, "!data8" => $data8, "!data9" => $data9, "!data10" => $data10, "!data11" => $data11, "!data12" => $data12);
                $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                $toEmail = $this->loggedInUser->email;
                $fromEmail = $this->config->item('site_admin_mail');
                $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

                //Notification message
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('update_buyer_confirm_success')));
                redirect('info/index/success');
            } //Form Validation End

        } //If - Form Submission End

        //Get Categories
        $this->outputData['categories'] = $this->skills_model->getCategories();

        //Get Countries
        $this->outputData['countries'] = $this->common_model->getCountries();

        //Conditions
        $conditions = array('users.id' => $this->loggedInUser->id);
        $this->outputData['userInfo'] = $this->user_model->getUsers($conditions);

        $conditions = array('user_contacts.user_id' => $this->loggedInUser->id);
        $this->outputData['userContactInfo'] = $this->user_model->getUserContacts($conditions);
        $this->outputData['userContact'] = $this->outputData['userContactInfo']->row();

        $this->load->view('buyer/editBuyerProfile', $this->outputData);

    } //Function editProfile End

    // --------------------------------------------------------------------

    /**
     * Loads _logo_check for uploading
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function _logo_check()
    {
        if (isset($_FILES) and $_FILES['logo']['name'] == '')
            return true;

        $config['upload_path'] = 'files/logos/';
        $config['allowed_types'] = 'jpeg|jpg|png|gif|JPEG|JPG|PNG|GIF';
        $config['max_size'] = $this->config->item('max_upload_size');
        $config['encrypt_name'] = TRUE;
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);

        if ($this->upload->do_upload('logo')) {
            $this->outputData['file'] = $this->upload->data();
            return true;
        } else {
            $this->form_validation->set_message('_logo_check', $this->upload->display_errors($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag')));
            return false;
        }
        //If end

    }//Function _logo_check End

    // --------------------------------------------------------------------


    // --------------------------------------------------------------------

    /**
     * Check for buyer mail id
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function _check_buyer_email($mail)
    {
        //language file
        $this->lang->load('enduser/buyerSignup', $this->config->item('language_code'));

        //Conditions
        $conditions = array('users.email' => $mail);
        $result = $this->user_model->getUsers($conditions);

        if ($result->num_rows() == 0) {
            return true;
        } else {
            $this->form_validation->set_message('_check_buyer_email', $this->lang->line('buyer_email_check'));
            return false;
        }
        //If end

    }//Function _check_buyer_email End

    // --------------------------------------------------------------------

    /**
     * Check for buyer mail id
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function _check_resendbuyer_email($mail)
    {

        //language file
        $this->lang->load('enduser/buyerSignup', $this->config->item('language_code'));
        //Get Role Id For Buyers
        $role_id = $this->user_model->getRoleId('buyer');

        //Conditions
        $conditions = array('users.email' => $mail, 'users.role_id' => $role_id, 'users.user_status' => '0');
        $result = $this->user_model->getUsers($conditions);
        $conditionsmail = array('users.email' => $mail, 'users.role_id' => $role_id);
        $resultmail = $this->user_model->getUsers($conditionsmail);

        $conditions2 = array('bans.ban_value' => $mail, 'bans.ban_type' => 'EMAIL');
        $result2 = $this->user_model->getBans($conditions2);
        //print_r($result2->num_rows() );
        if ($result2->num_rows() == 0 && $result->num_rows() == 1) {
            return true;
        } else if ($result2->num_rows() == 0 && $resultmail->num_rows() != 0) {
            $this->form_validation->set_message('_check_resendbuyer_email', $this->lang->line('buyer_email_ban'));
            return false;
        } else if ($result2->num_rows() != 0 || $resultmail->num_rows() == 0) {
            $this->form_validation->set_message('_check_resendbuyer_email', $this->lang->line('not_registered'));
            return false;
        }
        //If end

    }//Function _check_resendbuyer_email End


    // --------------------------------------------------------------------

    function _check_username($username)
    {
        //language file
        $this->lang->load('enduser/buyerSignup', $this->config->item('language_code'));

        //Get Role Id For Buyers
        $role_id = $this->user_model->getRoleId('buyer');

        //Conditions
        $conditions = array('users.user_name' => $username);
        $result = $this->user_model->getUsers($conditions);

        $conditions2 = array('bans.ban_value' => $username, 'bans.ban_type' => 'USERNAME');
        $result2 = $this->user_model->getBans($conditions2);

        if ($result->num_rows() == 0 && $result2->num_rows() == 0) {
            return true;

        } else {

            $this->form_validation->set_message('_check_username', $this->lang->line('username_unique'));

            return false;

        }
        //If end

    }//Function  _check_usernam End

    function _check_username_email($username){
        //language file
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));

        //Get Role Id For Buyers
        $role_id = $this->user_model->getRoleId('buyer');

        //Conditions
        $conditions = array('users.user_name' => $username);
        $where_or = array('users.email' => $username);
        $result = $this->user_model->getUsers($conditions, null, null, null, $where_or);

        //$conditions2 = array('bans.ban_value' => $username, 'bans.ban_type' => 'USERNAME');
        //$result2 = $this->user_model->getBans($conditions2);
        //&& $result2->num_rows() == 0

        if ($result->num_rows() > 0) {
            return true;
        } else {
            $this->form_validation->set_message('_check_username_email', $this->lang->line('user_not_exists'));
            return false;
        }
    }

    function attachment_file_check()
    {
        if (isset($_FILES['attach_file']) == TRUE  and $_FILES['attach_file']['name'] == ''){
            $this->form_validation->set_message('attachment_file_check',$this->lang->line('attach_file_required'));
            return false;
        }

        $file = upload_image($_FILES, 'message_attachment', 'attach_file');
        if (isset($file['file_name']) == TRUE) {
            $this->outputData['file'] = $file;
            return true;
        } else {
            $this->form_validation->set_message('attachment_file_check', $this->lang->line($file));
            return false;
        }
        //If end
    }

    // --------------------------------------------------------------------

    /**
     * Loads _check_activation_key for buyer
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function _check_activation_key($activation_key = 0)
    {
        //Conditions
        $conditions = array('users.activation_key' => $activation_key);
        $query = $this->user_model->getUsers($conditions);
        if ($query->num_rows == 1) {
            return true;
        } else {
            $this->form_validation->set_message('_check_activation_key', $this->lang->line('activation_key_validation'));
            return false;
        }
    }//Function _check_activation_key End

    // --------------------------------------------------------------------

    /**
     * View projects posted by a buyer
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function viewMyProjects()
    {
        $this->load->helper('reviews');
        $this->load->helper('invites');
        $this->load->helper('message');
        $this->load->helper('projectcases');
        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));

        $params = ($this->uri->uri_to_assoc())?$this->uri->uri_to_assoc():'';
        $this->outputData['params'] = $params;

        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        $page = isset($_GET['p'])?$_GET['p']:1;
        //$page = $this->uri->segment(3, '0');
        if (isset($page) === false or empty($page)) {
            $page = '1';
        }


        $page_rows = $this->config->item('listing_limit');
        $max = array($page_rows, ($page - 1) * $page_rows);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';

            //Conditions list project buyer tạo ra
            $order = array('projects.id', 'desc');
            $conditions = array('projects.creator_id' => $buyer_id);

            // filter project status
            $project_status = $this->input->post('project_status');
            if($project_status){
                $conditions['projects.project_status'] = $project_status;
                $params['st'] = $project_status;
            }elseif(isset($params['st'])){
                $conditions['projects.project_status'] = $params['st'];
            }

            $this->outputData['myProjects'] = $this->skills_model->getProjects($conditions, NULL, NULL, $max, $order);
            $created = $this->skills_model->getProjects($conditions);

            //Pagination
            $this->load->library('pagination');
            $config['base_url'] = site_url('buyer/viewMyProjects/');
            $config['total_rows'] = $created->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $this->outputData['pagination'] = $this->pagination->create_links(false, 'job');

            // load groups jobs
            $this->outputData['groups'] = $this->skills_model->countProjectByGroup(array('groups.parent_id =' => 0));

            // load dev watchlist
            $condition_watchlist = array('user_watchlist.user_id' => $buyer_id);
            $this->outputData['listFreelancer'] = $this->user_model->getFreelanceWatchlist($condition_watchlist,null,$max,null,null);

        }
        $this->load->view('buyer/myProjects', $this->outputData);

    }//Function viewMyProjects End

    function savedFreelancers()
    {
        $this->load->helper('projectcases');

        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));

        $params = ($this->uri->uri_to_assoc())?$this->uri->uri_to_assoc():'';
        $this->outputData['params'] = $params;

        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        $page = isset($_GET['p'])?$_GET['p']:1;
        //$page = $this->uri->segment(3, '0');
        if (isset($page) === false or empty($page)) {
            $page = '1';
        }

        $page_rows = $this->config->item('listing_limit');
        $max = array($page_rows, ($page - 1) * $page_rows);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';

            // load dev watchlist
            $condition = array('user_watchlist.user_id' => $buyer_id);
            $this->outputData['listFreelancer'] = $this->user_model->getFreelanceWatchlist($condition,null,$max,null,null);
            $created = $this->user_model->getFreelanceWatchlist($condition);

            //Pagination
            $this->load->library('pagination');
            $config['base_url'] = site_url('buyer/viewMyProjects/');
            $config['total_rows'] = $created->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $this->outputData['pagination'] = $this->pagination->create_links(false, 'job');
        }
        $this->load->view('buyer/savedFreelancers', $this->outputData);
    }

    function messages()
    {
        $this->load->helper('projectcases');

        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));

        $this->load->model('message_model');

        $params = ($this->uri->uri_to_assoc())?$this->uri->uri_to_assoc():'';
        $this->outputData['params'] = $params;

        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        $page = isset($_GET['p'])?$_GET['p']:1;
        //$page = $this->uri->segment(3, '0');
        if (isset($page) === false or empty($page)) {
            $page = '1';
        }

        $page_rows = $this->config->item('listing_limit');
        $max = array($page_rows, ($page - 1) * $page_rows);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            $this->load->library('pagination');
            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';

            // load message inbox
            $field_inbox = 'message.id,message.from_id,message.to_id,message.subject, message.message, message.created, message.status,users.user_name,users.logo, count(message.id) AS num_message';
            $condition_inbox = array('message.to_id' => $buyer_id);
            $group_inbox = array('message.from_id', 'message.subject');
            $this->outputData['message_inbox'] = $this->message_model->getMessageInbox($condition_inbox,$field_inbox,null,$max,null, $group_inbox);
            $count_message_inbox = $this->message_model->getMessageInbox($condition_inbox,'message.id',null,null,null, $group_inbox);
            $condition_inbox['message.status'] = 0;
            $this->outputData['count_unread'] = $this->message_model->getMessageInbox($condition_inbox, 'message.id');

            //Pagination
            $config['base_url'] = site_url('buyer/messages/#inbox/');
            $config['total_rows'] = $count_message_inbox->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $this->outputData['pagination_inbox'] = $this->pagination->create_links(false, 'ajax');

            // load message sent
            $condition = array('message.from_id' => $buyer_id);
            $this->outputData['message_send'] = $this->message_model->getMessageSend($condition,null,null,$max,null);
            $this->outputData['count_message_send'] = $count_message_send = $this->message_model->getMessageSend($condition);

            //Pagination
            $config['base_url'] = site_url('buyer/messages/#send/');
            $config['total_rows'] = $count_message_send->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $this->outputData['pagination_send'] = $this->pagination->create_links(false, 'ajax');

            $condition_archive = array('message.to_id' => $buyer_id, 'message.archive' => 1);
            $this->outputData['archive'] = $this->message_model->getMessageSend($condition_archive, null,null,$max,null);
            $this->outputData['count_archive'] = $count_archive = $this->message_model->getMessageSend($condition_archive);

            //Pagination
            $config['base_url'] = site_url('buyer/messages/#archive/');
            $config['total_rows'] = $count_archive->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $this->outputData['pagination_archive'] = $this->pagination->create_links(false, 'ajax');

        }
        $this->load->view('buyer/messages', $this->outputData);
    }

    function viewMessage()
    {
        $this->load->helper('projectcases');

        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));

        $this->load->model('message_model');

        $params = ($this->uri->uri_to_assoc())?$this->uri->uri_to_assoc():'';
        $this->outputData['params'] = $params;

        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        $id = $this->uri->segment(3,0);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            $condition_inbox = array('message.to_id' => $buyer_id);
            $condition_inbox['message.status'] = 0;
            $this->outputData['count_unread'] = $this->message_model->getMessageInbox($condition_inbox, 'message.id');

            // load message sent
            $condition_send = array('message.from_id' => $buyer_id);
            $this->outputData['count_message_send'] = $count_message_send = $this->message_model->getMessageSend($condition_send);

            $condition_archive = array('message.to_id' => $buyer_id, 'message.archive' => 1);
            $this->outputData['count_archive'] = $count_archive = $this->message_model->getMessageSend($condition_archive);

            $condition = array('message.id' => $id);
            $fields = 'message.subject, message.created';
            $message = $this->message_model->getMessageSend($condition, $fields)->row();

            $condition2 = "message.subject = ".$this->db->escape($message->subject). " AND (message.from_id = ".$this->db->escape($buyer_id)." OR message.to_id = ".$this->db->escape($buyer_id).")";
            $messages = $this->message_model->getMessageSend($condition2);

            // update status read
            $where_in = '';
            foreach ($messages->result() as $item) {
                $where_in[] = $item->id;
            }

            if($where_in != ''){
                $this->message_model->updateMessage(null, array('message.status' => 1), $where_in);
            }


            $this->outputData['messages'] = $messages;
            $this->outputData['message'] = $message;
            $this->outputData['buyer_id'] = $buyer_id;

        }
        $this->load->view('buyer/viewMessage', $this->outputData);
    }

    function ajaxGetMessageSend()
    {
        $result = '';
        $this->load->library('pagination');
        $this->load->model('message_model');

        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        //$page = isset($_GET['p'])?$_GET['p']:1;
        $page = ($this->input->post('p'))?$this->input->post('p'):1;
        if (isset($page) === false or empty($page)) {
            $page = '1';
        }

        $page_rows = $this->config->item('listing_limit');
        $max = array($page_rows, ($page - 1) * $page_rows);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';

            // load message sent
            $condition = array('message.from_id' => $buyer_id);
            $message_send = $this->message_model->getMessageSend($condition,null,null,$max,null);
            $count_message_send = $this->message_model->getMessageSend($condition);

            //Pagination
            $config['base_url'] = site_url('buyer/messages/#send/');
            $config['total_rows'] = $count_message_send->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $pagination_send = $this->pagination->create_links(false, 'ajax');

            $result = array(
                'items' => $message_send->result_array(),
                'pagination' => $pagination_send
            );
        }
        echo json_encode($result);
    }

    function ajaxGetMessageInbox()
    {
        $result = '';
        $this->load->library('pagination');
        $this->load->model('message_model');

        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        //$page = isset($_GET['p'])?$_GET['p']:1;
        $page = ($this->input->post('p'))?$this->input->post('p'):1;
        if (isset($page) === false or empty($page)) {
            $page = '1';
        }

        $page_rows = $this->config->item('listing_limit');
        $max = array($page_rows, ($page - 1) * $page_rows);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';

            // load message inbox
            $field_inbox = 'message.id,message.from_id,message.to_id,message.subject, message.message, message.created, message.status,users.user_name,users.logo, count(message.id) AS num_message';
            $condition_inbox = array('message.to_id' => $buyer_id);
            $group_inbox = array('message.from_id', 'message.subject');
            $message_inbox = $this->message_model->getMessageInbox($condition_inbox,$field_inbox,null,$max,null, $group_inbox);
            $count_message_inbox = $this->message_model->getMessageInbox($condition_inbox, 'message.id',null,null,null, $group_inbox);

            //Pagination
            $config['base_url'] = site_url('buyer/messages/#inbox/');
            $config['total_rows'] = $count_message_inbox->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $pagination_inbox = $this->pagination->create_links(false, 'ajax');

            $result = array(
                'items' => $message_inbox->result_array(),
                'pagination' => $pagination_inbox
            );
        }
        echo json_encode($result);
    }

    function ajaxGetMessageArchive()
    {
        $result = '';
        $this->load->library('pagination');
        $this->load->model('message_model');

        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        //$page = isset($_GET['p'])?$_GET['p']:1;
        $page = ($this->input->post('p'))?$this->input->post('p'):1;
        if (isset($page) === false or empty($page)) {
            $page = '1';
        }

        $page_rows = $this->config->item('listing_limit');
        $max = array($page_rows, ($page - 1) * $page_rows);

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;

            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';

            // load message inbox
            $condition_archive = array('message.to_id' => $buyer_id, 'message.archive' => 1);
            $archive = $this->message_model->getMessageSend($condition_archive, null,null,$max,null);
            $count_message_archive = $this->message_model->getMessageSend($condition_archive);

            //Pagination
            $config['base_url'] = site_url('buyer/messages/#archive/');
            $config['total_rows'] = $count_message_archive->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $pagination_archive = $this->pagination->create_links(false, 'ajax');

            $result = array(
                'items' => $archive->result_array(),
                'pagination' => $pagination_archive
            );
        }
        echo json_encode($result);
    }

    function ajaxMarkMessage()
    {
        $result = '';
        $this->load->model('message_model');

        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        $ids = ($this->input->post('ids'))?$this->input->post('ids'):'';
        $status = ($this->input->post('status'))?$this->input->post('status'):0;

        if ($this->loggedInUser && $ids != '') {
            $buyer_id = $this->loggedInUser->id;

            $condition = array('message.to_id' => $buyer_id);
            $where_in = $ids;
            if($status == 2){
                $updateData = array('message.archive' => 1);
            }else{
                $updateData = array('message.status' => $status);
            }
            $this->message_model->updateMessage($condition, $updateData, $where_in);

            if($status == 0 || $status == 1){
                $condition_inbox = array('message.to_id' => $buyer_id, 'message.status' => 0);
                $count_unread = $this->message_model->getMessageInbox($condition_inbox, 'message.id');
                $result['count_unread'] = $count_unread->num_rows();
            }elseif($status == 2) {
                $condition_archive = array('message.to_id' => $buyer_id, 'message.archive' => 1);
                $archive = $this->message_model->getMessageSend($condition_archive, null,null,array(10),null);
                $count_archive = $this->message_model->getMessageSend($condition_archive);
                $result['archive'] = $archive->result_array();
                $result['count_archive'] = $count_archive->num_rows();
            }
        }
        echo json_encode($result);
    }

    function createMessage()
    {
        $this->load->helper('projectcases');

        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));

        $this->load->model('message_model');
        //$this->load->model('user_model');

        $this->load->library('form_validation');
        //Load Form Helper
        $this->load->helper('form');
        $this->load->helper('file');

        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('users/login');
        }

        //Get buyer id
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;
        }
        $condition_inbox = array('message.to_id' => $buyer_id, 'message.status' => 0);
        $this->outputData['count_unread'] = $this->message_model->getMessageInbox($condition_inbox, 'message.id');

        $condition = array('message.from_id' => $buyer_id);
        $this->outputData['count_message_send'] = $count_message_send = $this->message_model->getMessageSend($condition);

        $condition_archive = array('message.to_id' => $buyer_id, 'message.archive' => 1);
        $this->outputData['count_archive'] = $count_archive = $this->message_model->getMessageSend($condition_archive);

        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        if ($this->input->post('btn_send')) {
            $this->form_validation->set_rules('send_to', 'lang:send_to_required', 'required|trim|xss_clean|callback__check_username_email');
            $this->form_validation->set_rules('subject', 'lang:subject_required', 'required|trim|xss_clean');
            $this->form_validation->set_rules('message', 'lang:message_required', 'required|trim|xss_clean');

            if(isset($_FILES['attach_file']) == TRUE  and $_FILES['attach_file']['name'] != ''){
                $this->form_validation->set_rules('attach_file', 'lang:file_required', 'callback_attachment_file_check');
            }

            if ($this->form_validation->run() == TRUE) {
                $username = $this->input->post('send_to', TRUE);
                $user = $this->user_model->getUsers(array('users.user_name' => $username), null, null, null, array('users.email' => $username))->row();
                $insertData = array();
                $insertData['from_id'] = $buyer_id;
                $insertData['to_id'] = $user->id;
                $insertData['subject'] = $this->input->post('subject', TRUE);
                $insertData['message'] = $this->input->post('message', TRUE);
                $insertData['created'] = time();

                if(isset($this->outputData['file'])){
                    $insertData['attach_file'] = $this->outputData['file']['file_name'];
                }

                $this->message_model->addMessage($insertData);
                $this->session->set_flashdata('flash_message', setMessage('success', $this->lang->line('Send message success')));
                redirect('buyer/messages');

            }else{
                $this->session->set_flashdata('flash_message', setMessage('error',  validation_errors()));
            }

        }
        $this->load->view('buyer/createMessages', $this->outputData);
    }

    function bookmarkProjects()
    {


        $buyer_id = $this->loggedInUser->id;

        //Get bookmark projects
        $condition_bookmark = array('bookmark.creator_id' => $buyer_id);
        $bookMark1 = $this->skills_model->getBookmark($condition_bookmark);

        //Get all users
        $this->outputData['getUsers'] = $this->user_model->getUsers();


        //pagination limit
        $page_rows = $this->config->item('mail_limit');
        $start = $this->uri->segment(3, 0);

        $limit[0] = $page_rows;
        $limit[1] = ($start - 1) * $page_rows;

        //Get all message trasaction with some limit
        $bookMark = $this->skills_model->getBookmark($condition_bookmark, NULL, NULL, $limit);
        $this->outputData['bookMark'] = $bookMark;


        //Pagination
        $this->load->library('pagination');
        $config['base_url'] = site_url('buyer/bookmarkProjects');
        $config['total_rows'] = $bookMark1->num_rows();
        $config['per_page'] = $page_rows;
        $config['cur_page'] = $start;
        $this->pagination->initialize($config);
        $this->outputData['pagination1'] = $this->pagination->create_links2(false, 'bookmarkProjects');

        $page = '0';

        $page_rows = $this->config->item('listing_limit');

        $max = array($page_rows, (1) * $page_rows);

        //Get Sorting order
        $field = $this->uri->segment(4, '0');
        $order = $this->uri->segment(5, '0');

        $orderby = array();
        if ($field)
            $orderby = array($field, $order);

        $this->outputData['order'] = $order;
        $this->outputData['field'] = $field;
        $this->outputData['page'] = $page;

        //Conditions
        $conditions = array('projects.creator_id' => $buyer_id, 'projects.project_status !=' => '2');
        $this->outputData['myProjects'] = $this->skills_model->getProjects($conditions, NULL, NULL, $max, $orderby);
        $created = $this->skills_model->getProjects($conditions);
        $conditions = array('projects.creator_id' => $buyer_id, 'projects.project_status =' => '2');
        $this->outputData['closedProjects'] = $this->skills_model->getProjectsByProvider($conditions);

        //Pagination
        $this->load->library('pagination');
        $config['base_url'] = site_url('buyer/viewMyProjects/');
        $config['total_rows'] = $created->num_rows();
        $config['per_page'] = $page_rows;
        $config['cur_page'] = 0;
        $this->pagination->initialize($config);
        $this->outputData['pagination'] = $this->pagination->create_links(false, 'project');

        $this->load->view('buyer/myProjects', $this->outputData);


    }


    /**
     * View buyer's profile
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function viewProfile()
    {
        //$userid=$this->uri->segment(3);

        //$condition = array('portfolio.user_id' => $userid);
        if (isset($this->loggedInUser->id)) {
            $condition = array('portfolio.user_id' => $this->loggedInUser->id);
            $this->outputData['portfolio'] = $this->user_model->getPortfolio($condition);

            //Load Language

        } elseif (!is_numeric($this->uri->segment(3))) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }
        $this->lang->load('enduser/viewProfile', $this->config->item('language_code'));
        $buyerId = $this->uri->segment(3, '0');

        $conditions = array('users.id' => $buyerId);

        $conditions2 = array('user_contacts.user_id' => $buyerId);

        $user = $this->user_model->getUsers($conditions);

        if ($user->num_rows() == 0) {
            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('user_not_available')));
            redirect('info');
        }

        $this->outputData['userDetails'] = $user;
        $urow = $user->row();
        $this->outputData['userContacts'] = $this->user_model->getUserContacts($conditions2);
        $country = $this->common_model->getCountries(array('country_symbol' => $urow->country_symbol));
        $this->outputData['country'] = $country->row();

        $conditions3 = array('projects.project_status' => '0', 'projects.creator_id' => $urow->id);
        $openProjects = $this->skills_model->getProjects($conditions3);
        $this->outputData['openProjects'] = $openProjects;

        $conditions4 = array('projects.project_status' => '2', 'projects.creator_id' => $urow->id);
        $closedProjects = $this->skills_model->getProjects($conditions4);
        $this->outputData['closedProjects'] = $closedProjects;

        $conditions5 = array('projects.project_status' => '3', 'projects.creator_id' => $urow->id);
        $cancelledProjects = $this->skills_model->getProjects($conditions5);
        
        $this->outputData['cancelledProjects'] = $cancelledProjects;
        $this->load->view('buyer/viewProfile', $this->outputData);

    }//Function _check_activation_key End

    // --------------------------------------------------------------------

    /**
     * review Programmers
     *
     * @access    private
     * @param    nil
     * @return    void
     */
    function reviewProgrammer()
    {

        //Load Language
        $this->lang->load('enduser/review', $this->config->item('language_code'));

        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to review programmer')));
            redirect('info');
        }

        if ($this->input->post('reviewProgrammer') == 1) {
            $insertData = array();
            $insertData['comments'] = $this->input->post('comment', TRUE);
            $insertData['rating'] = $this->input->post('rate', TRUE);
            $insertData['review_type'] = '2';
            $insertData['review_time'] = get_est_time();
            $insertData['project_id'] = $this->input->post('projectid', TRUE);
            $insertData['buyer_id'] = $this->loggedInUser->id;
            $insertData['provider_id'] = $this->input->post('providerid', TRUE);

            //Create Review
            $reviewId = $this->skills_model->createReview($insertData);

            //Update projects
            $this->skills_model->updateProjects($insertData['project_id'], array('provider_rated' => '1'));

            $condition = array('reviews.project_id' => $insertData['project_id']);
            $rev = $this->skills_model->getReviews($condition);

            //Send Mail
            $conditionUserMail = array('email_templates.type' => 'buyer_review');
            $result = $this->email_model->getEmailSettings($conditionUserMail);
            $rowUserMailConent = $result->row();

            //Get Project details
            $condition = array('projects.id' => $insertData['project_id']);
            $projectDetails = $this->skills_model->getProjects($condition, 'projects.project_name');
            $prjRow = $projectDetails->row();

            //Get User details
            $getuser = $this->user_model->getUsers(array('users.id' => $insertData['provider_id']));
            $user = $getuser->row();

            $splVars = array("!buyer_name" => $this->loggedInUser->user_name, "!project_name" => $prjRow->project_name, "!site_name" => base_url(), '!site_title' => $this->config->item('site_title'));
            $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
            $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
            $toEmail = $user->email;
            $fromEmail = $this->config->item('site_admin_mail');

            //Send mail
            //$this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

            if ($rev->num_rows() == 2) {

                //Increase number of reviews
                $num_reviews = ($user->num_reviews) + 1;

                //Rating
                if ($user->user_rating == 0)
                    $rating = $insertData['rating'];
                else
                    $rating = ($user->user_rating + $insertData['rating']) / 2;

                $tot_rating2 = ($rating * $num_reviews);

                //Update Provider
                $this->skills_model->updateUsers($insertData['provider_id'], array('user_rating' => $rating, 'num_reviews' => $num_reviews, 'tot_rating' => $tot_rating2));

                //Get buyer details
                $getHold = $this->skills_model->getRatingHold(array('rating_hold.user_id' => $this->loggedInUser->id, 'rating_hold.project_id' => $insertData['project_id']));
                $holdRow = $getHold->row();

                if ($getHold->num_rows() > 0) {

                    //Get Provider details
                    $getuser = $this->user_model->getUsers(array('users.id' => $this->loggedInUser->id), 'users.user_rating,users.num_reviews');
                    $buyerRow = $getuser->row();

                    //Rating
                    if ($buyerRow->user_rating == 0)
                        $rating = $holdRow->rating;
                    else
                        $rating = ($buyerRow->user_rating + $holdRow->rating) / 2;

                    //Increase number of reviews
                    $num_reviews = ($buyerRow->num_reviews) + 1;

                    $tot_rating = ($rating * $num_reviews);

                    //Update buyer
                    $this->skills_model->updateUsers($this->loggedInUser->id, array('user_rating' => $rating, 'num_reviews' => $num_reviews, 'tot_rating' => $tot_rating));

                    $condition2 = array('reviews.project_id' => $insertData['project_id'], 'reviews.buyer_id' => $this->loggedInUser->id, 'reviews.review_type' => '1');
                    $getrev = $this->skills_model->getReviews($condition2, 'reviews.id');
                    $revRow = $getrev->row();

                    $this->skills_model->updateReviews($revRow->id, array('reviews.hold' => '0'));
                }
            } elseif ($rev->num_rows() == 1) {

                $insertData2 = array();

                $insertData2['rating'] = $insertData['rating'];

                $insertData2['user_id'] = $insertData['provider_id'];

                $insertData2['project_id'] = $insertData['project_id'];

                $this->skills_model->insertRatingHold($insertData2);

                $this->skills_model->updateReviews($reviewId, array('reviews.hold' => '1'));
            }
            
            $result = array(
            	'status' => 'COMPLETED'
            );
            
            echo json_encode($result); die;

            //Notification message
            //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('review_added')));
            //redirect('info/index/success');
        }

        if (!is_numeric($this->uri->segment(3))) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }

        //Get project id
        $projectid = $this->uri->segment(3, '0');

        //Get Project details
        $condition = array('projects.id' => $projectid);
        $projectDetails = $this->skills_model->getProjects($condition);
        $this->outputData['projectDetails'] = $projectDetails;
        $prjRow = $projectDetails->row();

        //Get provider details
        $condition3 = array('users.id' => $prjRow->programmer_id);
        $providerDetails = $this->user_model->getUsers($condition3);
        $this->outputData['providerDetails'] = $providerDetails->row();

        //Get review details
        $condition2 = array('reviews.project_id' => $projectid, 'reviews.provider_id' => $prjRow->programmer_id, 'reviews.review_type' => '2');
        $this->outputData['reviewDetails'] = $this->skills_model->getReviews($condition2);

        $this->load->view('buyer/reviewProgrammer', $this->outputData);

    }//Function reviewProgrammer End

    // --------------------------------------------------------------------

    /**
     * Lists review of a provider
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function review()
    {
        //Load Language
        $this->lang->load('enduser/review', $this->config->item('language_code'));

        //Load helper
        $this->load->helper('reviews');

        if (!is_numeric($this->uri->segment(3))) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }
        $userId = $this->uri->segment(3, '0');

        //Get user details
        $conditions = array('users.id' => $userId);
        $user = $this->user_model->getUsers($conditions);
        $urow = $user->row();
        $this->outputData['userDetails'] = $urow;

        //Get reviews
        $condition2 = array('reviews.buyer_id' => $urow->id, 'reviews.review_type' => '1', 'reviews.hold' => '0');
        $this->outputData['reviewDetails'] = $this->skills_model->getReviews($condition2);

        $this->load->view('buyer/reviews', $this->outputData);

    } //Function review End

    function remove()
    {
        $project_id = $this->uri->segment(3);
        $conditions = array('bookmark.project_id' => $project_id, 'bookmark.creator_id' => $this->loggedInUser->id);
        $bookMarks = $this->common_model->deleteTableData('bookmark', $conditions);
        $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Bookmark deleted successfully'));
        redirect('buyer/viewMyProjects/');
    }


    function loadFormAddScore(){
        // load language
        $this->lang->load('enduser/score', $this->config->item('language_code'));
        $this->lang->load('enduser/editProfile', $this->config->item('language_code'));
        //Check Whether User Logged In Or Not
        if (!isset($this->loggedInUser->id)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be login access to this page')));
            redirect('info');
        }

        // pagination - history - balance
        $page_rows = 3;
        $page = $this->uri->segment(3,'0');
        if(isset($page)===false or empty($page)){
            $page = 1;
        }
        $limit = array($page_rows,($page - 1) * $page_rows);

        // show history balance
        $user_id = $this->session->userdata('user_id');
        $this->load->model("transaction_model");
        $condition = array("history_balance.user_id" => $user_id);
        $history = $this->transaction_model->getHistoryBalance($condition,$limit);
        $history_num_row = $this->transaction_model->getHistoryBalance($condition);
        $this->outputData['history'] = $history->result();
        // pagination continue
        $this->load->library('pagination');
        $config['base_url']     = site_url('buyer/loadFormAddScore/');
        $config['total_rows']   = $history_num_row->num_rows();        
        $config['per_page'] = $page_rows; 
        $config['cur_page'] = $page;
        $config['next_link']    = 'Next';
        $config['prev_link']    = 'Prev';
        $this->pagination->initialize($config);     
        $this->outputData['pagination']   = $this->pagination->create_links(false,'history_balance');

        // show user information
        $user_id = $this->session->userdata('user_id');
        $condition = array(
            "users.id" => $user_id
        );
        $field = "roles.role_name,users.user_name,users.resume,users.name,users.profile_desc,users.role_id,users.country_symbol,users.message_notify,users.password,users.email,users.city,users.state,users.profile_desc,users.rate,users.project_notify,users.user_status,users.activation_key,users.created,users.last_activity,users.num_reviews,users.user_rating,users.logo,users.refid,user_categories.user_categories";
        $user_info = $this->user_model->getUsers($condition,$field);
        $this->outputData['user_info'] = $user_info->row_array();

        // show user balance
        $condition = array("user_balance.user_id" => $user_id);
        $fields = "user_balance.id,user_balance.user_id,user_balance.amount,user_balance.frozen,user_balance.bonus";
        $user_balance = $this->user_model->getUserBalance($condition,$fields);
        $this->outputData['user_balance'] = $user_balance->row_array();

        //load validation libraray
        $this->load->library('form_validation');
        $this->load->view("score/insertScore",$this->outputData);
    }

    function insertScore(){
        // load language
        $this->lang->load('enduser/score', $this->config->item('language_code'));
        //load validation libraray
        $this->load->library('form_validation');
        // load transaction helper
        $this->load->helper("transaction");

        //Check Whether User Logged In Or Not
        if (!isset($this->loggedInUser->id)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be login access to this page')));
            redirect('info');
        }

        $user_id = $this->session->userdata('user_id');
        $created = get_est_time();
        $this->form_validation->set_rules('score', 'lang:score_input', 'required|xss_clean');
        if ($this->form_validation->run()) {
            $amount = $this->input->post("score");
            insertAmountHistory($user_id,$amount,$created);
            updateAmount($user_id,$amount,$created);

        }
        redirect('buyer/editProfileUpdate/');

        
    }// end function





    //---------------------------------------------------------------------

    /**
     * editProfile for both buyer and programmer for edit his profile
     *
     * @access    public
     * @param    nil
     * @return    void
     */

    function editProfileUpdate(){
        //language file
        $this->lang->load('enduser/editProfile', $this->config->item('language_code'));
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));

        //Check Whether User Logged In Or Not
        if (!isset($this->loggedInUser->id)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be login access to this page')));
            redirect('info');
        }

        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');
        $this->load->helper('alert');

        $conditions = array('groups.is_deleted' => 0);
        $fields = array('groups.group_name','groups.id','groups.parent_id');
        $listCategories = $this->skills_model->getGroup($conditions,$fields);

        foreach($listCategories->result() as $item){
            if($item->parent_id == 0) {
                $this->outputData['listParentCategories'][$item->id]['id'] = $item->id;
                $this->outputData['listParentCategories'][$item->id]['name'] = $item->group_name;
            }
        }

        foreach($this->outputData['listParentCategories'] as $item){
            foreach($listCategories->result() as $item2){
                if($item['id'] == $item2->parent_id){
                    $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['id'] = $item2->id;
                    $this->outputData['listParentCategories'][$item['id']]['child'][$item2->id]['name'] = $item2->group_name;

                }
            }
        }


        $this->outputData['categories'] = $this->skills_model->getCategories();

        $this->outputData['userCategories'] = $this->user_model->getUserSkill($this->loggedInUser->id);

        $this->outputData['menuActive'] = array('setting_menuActive' => 'active');

        $condition = array('groups.is_deleted' => 0,'groups.parent_id' => 0);
        $fields = array('groups.group_name','groups.id');
        $this->outputData['groupParent'] = $this->skills_model->getGroups($condition,$fields);
        //Validation form
        //Intialize values for library and helpers
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        if ($this->input->post('submit', TRUE)) {
            //Set rules
            $this->form_validation->set_rules('title', 'lang:name', '   xss_clean');
            $this->form_validation->set_rules('profile_desc', 'lang:Profile Desc', 'xss_clean');
            $this->form_validation->set_rules('group_parent', 'lang:group_parent', 'xss_clean');
            $this->form_validation->set_rules('year_experience', 'lang:year_experience', 'xss_clean');
            $this->form_validation->set_rules('facebook', 'lang:facebook', 'xss_clean');
            $this->form_validation->set_rules('twitter', 'lang:twitter', 'xss_clean');
            $this->form_validation->set_rules('google_plus', 'lang:google_plus', 'xss_clean');
            $this->form_validation->set_rules('linkedin', 'lang:linkedin', 'xss_clean');
            $this->form_validation->set_rules('github', 'lang:github', 'xss_clean');
            $this->form_validation->set_rules('your_website', 'lang:your_website', '');
            $this->form_validation->set_rules('group_ids', 'lang:group_ids', 'xss_clean');


            if ($this->form_validation->run()) {
                //print_r($_POST);exit;
                $updateData['title'] = $this->input->post('title',TRUE);
                $updateData['profile_desc'] = $this->input->post('profile_desc',TRUE);
                $updateData['group_id'] = $this->input->post('group_parent',TRUE);
                $updateData['facebook'] = $this->input->post('facebook',TRUE);
                $updateData['google_plus'] = $this->input->post('google_plus',TRUE);
                $updateData['linkedin'] = $this->input->post('linkedin',TRUE);
                $updateData['github'] = $this->input->post('github',TRUE);
                $updateData['twitter'] = $this->input->post('twitter',TRUE);
                $updateData['year_exp'] = $this->input->post('year_experience',TRUE);
                $updateData['your_website'] = $this->input->post('your_website',TRUE);
                if(count($this->input->post('group_ids',TRUE)) > 0 && (is_array($this->input->post('group_ids',TRUE)))){
                    $updateData['group_ids'] = implode(',',$this->input->post('group_ids',TRUE));
                }else{
                    $updateData['group_ids'] = "";
                }
                if(count($this->input->post('project_categories',TRUE)) > 0 && (is_array($this->input->post('project_categories',TRUE)))){
                    $projectCategories = array_unique($this->input->post('project_categories',TRUE));

                    $updateUserCategories['user_categories'] = implode(',',$projectCategories);
                }else{
                    $updateUserCategories['user_categories'] = "";
                }
//                print_r($this->input->post('group_ids',TRUE));exit;
                if($this->input->post('group_ids',TRUE) != "") {
                    foreach ($listCategories->result() as $item) {
                        if (in_array($item->id, $this->input->post('group_ids', TRUE))) {
                            $groupParent[] = $item->parent_id;
                        }
                    }
                    $updateData['group_id'] = implode(',', array_unique($groupParent));
                }else{
                    $updateData['group_id'] = "";
                }


                $updateKey = array('id' => $this->loggedInUser->id);
                $conditionUpdateUserCategories = array('user_id' => $this->loggedInUser->id);

                if(count($this->outputData['userCategories']) > 0)
                    $this->user_model->updateCategories($conditionUpdateUserCategories,$updateUserCategories);
                else {
                    $insertUserCategories = array('user_categories.user_id' => $this->loggedInUser->id,'user_categories.user_categories' => $updateUserCategories['user_categories']);
                    $this->user_model->insertUserCategories($insertUserCategories);
                }

                $this->user_model->updateUser($updateKey, $updateData);

                if(updatePercentProfile() == TRUE) {
                    $this->session->set_flashdata('edit_profile_success', $this->lang->line('Edit profile success'));
                    redirect('programmer/viewProfile/'.$this->loggedInUser->id);
                }
            }else{

            }

        }

        $this->outputData['groupCategory'] = $this->skills_model->getGroupsWithCategory();
        $condition = array('categories.is_deleted' => 0);
        $fields = array('categories.id','categories.category_name');
        $listCategory = $this->skills_model->getCategory($condition,$fields);

        if($listCategory->num_rows() > 0){
            foreach($listCategory->result_array() as $item){
                $this->outputData['listCategory'][$item['id']] = $item['category_name'];
            }
        }




        // show user information
        $user_id = $this->session->userdata('user_id');
        $condition = array(
            "users.id" => $user_id
        );
        $field = "users.title,roles.role_name,users.user_name,users.resume,users.name,users.profile_desc,users.role_id,users.country_symbol,users.message_notify,users.password,users.email,users.city,users.state,users.profile_desc,users.rate,users.project_notify,users.user_status,users.activation_key,users.created,users.last_activity,users.num_reviews,users.user_rating,users.logo,users.refid,user_categories.user_categories,users.year_exp,users.facebook,users.google_plus,users.twitter,users.linkedin,users.github,users.your_website,users.group_id,users.group_ids,users.employment_history";
        $user_info = $this->user_model->getUsers($condition,$field);

        $this->outputData['user_info'] = $user_info->row_array();


        // show user balance
        $condition = array("user_balance.user_id" => $user_id);
        $fields = "user_balance.id,user_balance.user_id,user_balance.amount,user_balance.frozen,user_balance.bonus";
        $user_balance = $this->user_model->getUserBalance($condition,$fields);
        $this->outputData['user_balance'] = $user_balance->row_array();



        // show Portfolio
        $condition = array(
            'portfolio.user_id' => $user_id
        );
        $field = "portfolio.id, portfolio.title, main_img, description";
        $portfolio = $this->user_model->getPortfolio($condition,$field);
        $this->outputData['portfolio'] = $portfolio;

        //pagination limit
        $page_rows = $this->config->item('mail_limit');
        $start = $this->uri->segment(3, 0);
        if ($start > 0)
            $start = ($start - 1) * $page_rows;

        $limit[0] = $page_rows;
        $limit[1] = $start;
        //var_dump($limit); die;
        //Pagination
        $this->load->library('pagination');

        //Get review details
        if($this->outputData['user_info']['role_id'] == 1){
            $fields = "reviews.id,reviews.rating,reviews.provider_id,reviews.review_time,reviews.buyer_id,,reviews.comments,users.user_name,users.id AS user_id,users.logo,users.num_reviews,users.user_rating";
            $condition2 = array('reviews.buyer_id' => $user_id, 'reviews.review_type' => '2');
            $countReviews = $this->skills_model->getReviewsBuyer($condition2);

            $this->outputData['reviews'] = $this->skills_model->getReviewsBuyer($condition2, $fields, NULL, $limit);

            $config['base_url'] = site_url('buyer/editProfileUpdate');
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $start;
            $config['total_rows'] = $countReviews->num_rows();
            $this->pagination->initialize($config);

            $this->outputData['pagination'] = $this->pagination->create_links2(false, 'editProfileUpdate');
        }elseif($this->outputData['user_info']['role_id'] == 2){
            $fields = "reviews.id,reviews.rating,reviews.provider_id,reviews.review_time,reviews.buyer_id,,reviews.comments,users.user_name,users.id AS user_id,users.logo,users.num_reviews,users.user_rating";
            $condition2 = array('reviews.provider_id' => $user_id, 'reviews.review_type' => '1');
            $countReviews = $this->skills_model->getReviewsBuyer($condition2);

            $this->outputData['reviews'] = $this->skills_model->getReviewsProvider($condition2, $fields, NULL, $limit);

            $config['base_url'] = site_url('buyer/editProfileUpdate');
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $start;
            $config['total_rows'] = $countReviews->num_rows();
            $this->pagination->initialize($config);

            $this->outputData['pagination'] = $this->pagination->create_links2(false, 'editProfileUpdate');
        }

        $this->load->view("buyer/editBuyerProfile",$this->outputData);


    }

    function checkEmailIsExists(){
        $email = $this->input->post("email_fp",TRUE);
        $result = $this->user_model->checkEmailExists($email);
        if(count($result->row_array()) == 0){
            echo "false";
        }else{
            echo "true";
        }
    }

    function checkUserEmailInfo(){
        $email = $this->input->post("email",TRUE);
        $result = $this->user_model->checkEmailExists($email);
        if(count($result->row_array()) == 0){
            echo "true";
        }else{
            echo "false";
        }
    }

    function checkUserNameInfo(){
        $username = $this->input->post("username");
        $result = $this->user_model->checkUsernameExists($username);
        if(count($result->row_array()) == 0){
            echo "true";
        }else{
            echo "false";
        }
    }

    function checkUserPassExists(){
        if($this->uri->segment(3,'0')){
            $id = $this->uri->segment(3,'0');
            $pass = md5($this->input->post("pwd-new",TRUE));
            $condition = array(
                "users.id" => $id,
                "users.password" => $pass
                );
            $result = $this->user_model->checkPassExists($condition);
            if(count($result->row_array()) == 0){
                echo "true";
            }else{
                echo "false";
            }
        }
        
    }

    function registerFacebook(){
      //echo $this->input->post('email');exit;
        $products = json_decode($this->input->post('response',TRUE));

        foreach($products as $k => $item){
            $array[$k] = $item;
        }
        if( !($this->session->userdata('infoFacebook')) ) {
            $this->session->set_userdata('infoFacebook', $array);
        }else{
            $this->session->unset_userdata('infoFacebook');
            $this->session->set_userdata('infoFacebook', $array);
        }
        $conditions = array('email' => $this->input->post('email',TRUE));
        $fields = array('users.email','users.id as id','roles.role_name','users.facebook_id');
        $user = $this->user_model->getUsers($conditions,$fields);
        if($user->num_rows() > 0){
            $result = $user->row();
            if($result->facebook_id != 0){
                echo json_encode(array("status" =>'email-facebook-exist'));exit;
            }else {
                echo json_encode(array("status" => 'email-exist'));
                exit;
            }
        }else{
            echo json_encode(array('status' => 'not-exist'));exit;
        }
    }
	
	function registerGoogle(){
		$infoGoogle = json_decode(str_replace('\"', '', $this->input->post('response',TRUE)));
		//var_dump($infoGoogle); die;
        $arrGoogle = array(
            'google_id' => $infoGoogle->id,
            'display_name' => $infoGoogle->displayName,
            'gender' => $infoGoogle->gender,
            'avartar' => $infoGoogle->image->url,
            'birthday' => isset($infoGoogle->birthday)?$infoGoogle->birthday:'',
        );

		$ssGoogle = $this->session->userdata('infoGoogle');
        if( $ssGoogle != FALSE ) {
            $this->session->set_userdata('infoGoogle', $arrGoogle);
        }else{
            $this->session->unset_userdata('infoGoogle');
            $this->session->set_userdata('infoGoogle', $arrGoogle);
        }

		$conditions = array('email' => $this->input->post('email',TRUE));
		$fields = array('users.email','users.id as id','roles.role_name', 'users.google_id');
		$user = $this->user_model->getUsers($conditions,$fields);
		if($user->num_rows() > 0){
            $row = $user->row();
            if($row->google_id == 0){
                echo json_encode(array("status" =>'google-exist'));exit;
            }else{
			    echo json_encode(array("status" =>'email-exist'));exit;
            }
		}else{
			echo json_encode(array('status' => 'not-exist'));exit;
		}
    }

    function insertProjectsRandomIntoDBUpdate(){
        /* ---------- insert project vào bảng project ---------- */
        $client_id = $this->user_model->getClientId();
        $freelancer_id = $this->user_model->getFreelancerId();
        $show = array();
        for($k=0; $k<8; $k++){
            $rand = mt_rand(0,5);
            $view = mt_rand(1,100);
            $bget_min0 = array('30','250','750','1500','3000','5000');
            $bget_max1 = array('250','750','1500','3000','5000','7000');
            $rand1 = mt_rand(0,4);
            $group_id = array('19','20','21','22','26');
            $group_ids = array(
                array('11','23','24','25'),
                array('13','14','15'),
                array('16','17'),
                array('18','31','32'),
                array('34','35','36')
            );

            $group_ids_rand = array();
            for ($h=0; $h <count($group_ids[$rand1]) -1 ; $h++) {
                $group_ids_rand[] = $group_ids[$rand1][mt_rand(0,sizeof($group_ids[$rand1]) -1)];
            }
                $insert_groupids = implode(',', $group_ids_rand);
            $pr_categories = $this->user_model->getGroupidInCategory($insert_groupids);
            $cate_rand1 = array();
            for($i=0; $i< 3; $i++){
                $cate_rand1[] = $pr_categories[mt_rand(0,sizeof($pr_categories) - 1 )];
            }
            $categories_rand1 = implode(',',$cate_rand1);
            /* lấy đúng project và description dựa vào rand_project */
            $project_names_arr = array(
                'CNN Breaking US & World News',
                'Lifesum – Calorie Counter',
                'The Guardian',
                'News Republic – Smarter news',
                'Real Boxing',
                'Fishing Paradise 3D Free+',
                'Wrestling Revolution 3D',
                'FIFA 15 Ultimate Team',
                'Real Basketball',
                'Golf Star™',
                'Beautiful Widgets Pro',
                'Smart Launcher 2',
                'Asphalt 8: Airborne',
                'Google Talkback',
                'Animal Voyage:Island Adventure',
                'Star flying live wallpaper',
                'Amazing Candle',
                'Nature relax music',
                'Nature Sounds Relax and Sleep',
                'Foot massage Acupressure',
                'Relax Melodies: Sleep & Yoga',
                'Stretch Exercises',
                'Baristame - Coffee Guide PRO',
                'OfficeSuite 7 Pro (PDF&Fonts)',
                'PrinterShare™ Premium Key',
                'Hancom office Hwp 2010',
                'Monkey Preschool Lunchbox',
                'English Study TFLAT',
                'Hazard Perception Test DTS',
                'Laban Dict: English Vietnamese',
                'AllCast Premium',
                'Geocaching',
                'Akinator the Genie',
                'Slingplayer for Phones',
                '4shared PRO:download any files',
                'Sleep as Android Unlock',
                'My Movies Pro - Movie Library',
                'Vivino Wine Scanner Pro',
                'Flash Alerts on Call and SMS',
                'BeerSmith 2 Mobile Homebrewing',
                'Galaxy Tarot Pro',
                'Viz Profanisaurus',
                'Champions League 2014/2015',
                'The Bards Tale',
                'FINAL FANTASY VI',
                'Buff Knight - RPG Runner',
                'ONLINE RPG AVABEL [Action]',
                'Summoners War: Sky Arena',
                'Galaxy Legend',
                'Need for Speed™ Most Wanted',
                'Earn to Die',
                'Real Drift Car Racing',
                'Bike Mayhem Mountain Racing',
                'Reckless Racing 3',
                'Cars: Fast as Lightning',
                'MONOPOLY',
                'Ticket to Ride'
            );

            $project_description_arr = array(
                "The redesigned CNN App for Android has been rebuilt and redesigned for use on both your phone and tablet. Stay informed with the latest headlines and original stories from around the globe. Follow up-to-the-minute reporting with breaking news alerts and live video. Share stories and videos and comment on top stories.",
                "Lifesum coaches you to track what you eat and your exercise every day. It helps you to make better food choices and improve your habits. The app is perfect if you want to lose weight, control your daily food habits or if you work out a lot and need to optimize your nutritional intakes.",
                "Specially crafted for tablets and phones, this app brings you breaking news and full access to the Guardian's award-winning content. Tailor your home screen with the sections that matter most to you, follow your favourite writers and stories for personal alerts, keep reading when you’re offline, and save content for as long as you like.",
                "The smarter news app - offering the most comprehensive daily breaking news coverage from over 1,000 licensed & trusted news sources worldwide.",
                "Real Boxing™ brings you the most exhilarating, no holds barred fighting ever seen on Android. Featuring ultra-realistic motion capture from real boxers plus amazing graphics from the powerful Unreal Engine, you’ll feel every hook, jab and uppercut in each combo you unleash upon your opponent - now more exciting than ever with the new Combo Update. You can get even more physical by using the Wikipad tablet and controller combo, as well as a range of other controllers to play Real Boxing. ",
                "Realistic fishing action at your fingertips! 8+ million installs worldwide! Awesome 3D graphics, multiplayer action. Build and manage your very own fish farm and travel to remote, exotic locations with your guide.... legendary fisherman the Bass Professor!",
                "Discover brand new Single Player modes, endless Missions and rewarding Mini Game with countless hours of gameplay.",
                "From the English Premier League, La Liga, and MLS, to the German Bundesliga and beyond. Take the thrills with you wherever you are with the most authentic ",
                "Real Basketball is an addictive game designed for basketball fans, which it offers single player or multiplayer options, as well as many fun game modes where you can show off your basketball skills",
                "Introducing Golf Star, the greatest golf game you\’ll ever play, featuring realistic graphics, golfing techniques mastered by the pros, and a simulation powered by real physics-based gameplay. Play with golfers from all over the world",
                "Beautiful Widgets was the first application to achieve one million paid downloads. It was listed as “Google Editor’s choice” for more than one year and has been listed as one of the top 10 paid applications in the Google Play Store for more than 4 years now. Just like 4 million other beautiful widgets users, take advantage of comprehensive weather forecast information and the HD version of your other favorite clock widgets, weather widgets, compatible with phones and tablet",
                "Smart Launcher 2 is an innovative launcher, featuring minimalist design, low resource requirements and a user-friendly interface that allows you to launch any application with just a few taps. SL2 has been downloaded by over ten million people!",
                "The best Android arcade racing game series reaches a new turning point! Perform dynamic, high-speed aerial stunts in an intense driving experience powered by a brand-new physics engine!",
                "TalkBack is an Accessibility Service that helps blind and vision-impaired users interact with their devices. Talkback adds spoken, audible, and vibration feedback to your device. It is a system application that was pre-installed on most devices and is updated when the accessibility service is improved.",
                "Explore mysterious islands and rescue stranded animals that need your help! Save exotic creatures from flooded islands and bring them safely home to build your very own animal paradise!Start playing this intriguing and unique animal rescue game today!",
                "Star flying live wallpaper. Star flying on sky with meteors. Can load your phone`s photo in bacground in set.",
                "Amazing Candle is a fun FREE app that lets you create a real candle in your phone! It's the most photo-realistic candle that you can control: flick to ignite the flame, flick again to close. Repeat until stress is relieved. You could blow out or blow on the candle by holding the microphone up to your mouth - or - swipe your finger up and down to light the candle.",
                "Nature relaxing music allows reaching a relax state. The best android nature sounds are here. If you want to relax daily, don't search more. Do you have stress every day? Get now this relax music and feel instantly released. If you are searching a good app with nice design, customizable and with good quality nature music, this is your app.",
                "Want to relax for 10 minutes during the day at home or in office? Want to improve brain work? Or may be want to dream about beautiful nature landscapes? Increase concentration? Then choose from a list of 6 different good quality nature relaxing sounds (sounds of nature) which include thunder, ocean sounds, sea, birds sounds, rain, night in jungle, water sounds, waterfall, nature and start your personal audio therapy.",
                "The effect of foot massage is same as elixir of life. The foot is the foundation of health.",
                "Relax Melodies is the LEADER in personalized relaxation and sleep assistance. No more lacking of sleep or insomnia for you! The sleep that you need and want is waiting for you. Relax Melodies and its many features such as high quality white noise sounds, music melodies and complete customizable mixes will help you sleep like never before!",
                "Suffering from constant backaches and waist pains? Always feeling energies drained after a day's work? Or caught in low spirits with too much pressure? A regular stretching program can bring about more benefits than you have imagined. Stretch Exercises provides a most convenient way to stretch with or without a simple chair. Professionally designed but easily learnt, Stretch Exercises make use of and simplify various Yoga poses for everyone, regardless of flexibility, to enjoy total relaxation and refreshment through daily stretching.",
                "All images are copyright to BARISTAME and may not be used without direct approval. Please contact dabs.apps at gmail dot com for questions or comments about the images or content. If there are any inaccuracies please send an email and I will make changes if they are correct.",
                "OfficeSuite Pro allows you to view, create, edit, print and share Microsoft Word, Excel and PowerPoint files on the go. You can also open attachments and see PDF files on an Android based phone or tablet with our feature-rich mobile office solution. Bring your office with you and stay productive wherever you go!",
                "This key unlocks premium features of free PrinterShare application. It cannot be used on its own! If you haven't done so already, please install main free PrinterShare app and print test page before purchasing this key. With PrinterShare Mobile Print you can instantly print Office documents, bills and invoices (Word, Excel, PowerPoint, PDF, text files and more) directly from your tablet or phone (from internal memory, SD card or cloud source such as Google Drive / Google Docs) to a printer right next to you or anywhere in the world!",
                "Hancom Office Hwp 2010 for Android’ is the latest office product for mobile compatible with. Hancom Office Hwp 2010’. Please check out the device supported because it's different from ‘Hancom Office Hwp 2014 for Android",
                "6 different games that teach kids about colors, letters, counting, differences, and matching. Lovable animated monkey helps kids along as they play the games. Dozens of sounds and voice recordings of colors, letters, fruit names, and more. Animated Stickers! Kids get a sticker reward after every other game they win. Designed for preschoolers -- no confusing menus or navigation.",
                "Listening basics, learn English from conversations have included the translation , all English words in this software are the corresponding translation. Collection of best English learning videos on Youtube , to help you practice English listening effectively. Collection 3000 basic English vocabulary dictionary Oxford , have interpreted that pronunciation , this is very useful for beginners who learn English. Collection 1000 common English phrases according to the Oxford Dictionary , there are interpretations , pronounced , by many diverse topics so you can learn ",
                "This app was invaluable, in conjunction with the partnering Test Questions app, in helping me pass first time. A must have for anyone sitting the Theory Test",
                "Basic learning English - English Grammar. Software to learn English grammar on android in Vietnam. Helps you learn English effectively everyday. Using OFFLINE, help you learn English more convenient when there is no Internet. List of all diversity, help you learn English from basic to advanced.",
                "This app is just the License key for AllCast. You must also download the free version of the app. IF YOU ARE HAVING LICENSE ISSUES, MAKE SURE YOU HAVE THE LATEST VERSION OF FREE AND THE LATEST LICENSE INSTALLED!",
                "Geocaching is the real-world treasure hunting adventure that’s happening right now, all around you. Geocachers use this app to seek out treasures called geocaches. These containers are cleverly hidden by geocachers from the 6-million-strong global community. There are over two million geocaches hidden around the world, so there’s almost certainly one near you. All you need to begin your adventure is a smartphone with this app and a free Geocaching account.",
                "With MyWorld, Akinator knows you better than even! Akinator can read your mind and tell you what character you are thinking about, just by asking a few questions. Think of a real or fictional character and Akinator will try to guess who it is. Will you dare challenge the Genie?",
                "Get the most out of your Sling devices and turn your Android phone into a TV with Slingplayer for Phones. With a Sling device at home and Slingplayer on your Android phone, enjoy live or recorded TV over 3G, 4G, or WiFi. Take control of your TV and DVR from your mobile device. Flip through channels with the virtual remote control. Pause, fast-forward, rewind, and even schedule DVR recordings.",
                "4shared is a special service that lets you store all your files at the safe place. The service lets you download files from 4shared database and share them with friends. Install AD FREE 4shared Pro, especially designed for Android, to manage your 4shared account wherever you are. Get 4shared Pro on the lowest price to enjoy such features",
                "Unlocks the Sleep as Android application - the alarm clock with sleep cycle tracker. Install this Unlock and enjoy all features without any limitations every day: sleep tracking, graph history, sharing graphs on FaceBook, nature alarms (birds, sea, storm...), fall in sleep with music (volume down when asleep), captcha. Sleep as Android is a smart alarm clock with sleep cycle tracking. Wakes you gently in optimal moment for pleasant mornings.",
                "Important Notice! This application is for managing a movie collection library. You can not download or watch movies with it. My Movies for Android allows you to catalog your entire movie collection library from our high quality online data service containing data for more than 800,000 DVD, Blu-ray and HD DVD titles from various countries. If you have one or more titles that is not in our service, you can report it and it will be created within 48 hours by our staff - a service you will not find elsewhere.",
                "Vivino simplifies your path to enjoying great wines. The app helps you remember your favorites, learn more about wine, and which one to choose for next occasion. Snap a photo of any wine, and while you have a sip we automatically recognize it from our database of more than 3 million wines. If the app doesn’t match it immediately, our team will do it for you as quickly as we can. Discover all you want to know about wines, explore friend’s ratings and get personal recommendations based on your taste, simply browse wines in nearby stores or locate the ones on your Vivino Wish List.",
                "When you receive a call, new text message, the flash will blink. One of the cool flashlight alert or flash alert Android application in the play store. Very useful in the dark or at night when you do not want to hear ringtones. Do you want flash on call then download this application.",
                "Need to create great homebrewing beer recipes on the go? BeerSmith 2, the world's top selling home brewing software, comes to Android. BeerSmith Mobile gives you all the tools to design, edit and brew your best beer from your phone or tablet. BeerSmith home brewing is tightly integrated with our recipe cloud service and desktop BeerSmith program making it easy to create recipes from your desktop computer or phone and share them transparently.",
                "Pull Tarot cards, do your own Tarot readings and learn all about Tarot Cards! Whether you're brand new to Tarot cards or an experienced professional, Galaxy Tarot is made to guide and delight you!",
                "The brand new Profanisaurus Das Krapital App is the ultimate swearing dictionary. Cross-linked entries enable you to finally make sense of what a sleeping fruit bat is and why you'd never want to mention knuckle glitter in polite company. Browse profanities by topics ranging from verbal to the loo, alphabetically or at random, and make your own list of favoured words so that you can find the perfect term to define those difficult situations when you're on the train home next to a Pocket Fisherman.",
                "Live the emotions of Champions League 2014 / 2015, from the preliminary rounds straight to the final, by sharing your comments and passion with football fans from all around the world! With Champions 2014/2015 you always have real time results, standings.",
                "You are the Bard, a selfish rogue weary of pointless sub-quests and rat-infested cellars. Through magical song you summon characters to join you in battle, heal your party, and take damage on your behalf. Ready your weapon as you embark on a quest for coin and cleavage!",
                "FINAL FANTASY VI first debuted in 1994 as the sixth installment in the iconic FINAL FANTASY series. Innovations included the ability to play all the main characters as the game's protagonist, and to this day, its epic story intertwining each of their fates is still highly rated and wildly popular. The characters' dramatic performances are also highly rated, including the catastrophe occurring midway through, which delivers a particular emotional jolt to players.",
                "Play the EPIC retro RPG runner – Buff Knight! Developed by a 1 man studio, this pixel graphic game has stormed the top charts in Korea. Now it’s your turn. Slay the dragon! Save the princess! Buff Knight!",
                "AVABEL ONLINE is a 3D-MMORPG that delivers the best in smartphone graphics. Users can enjoy the games exhilarating features, such as smooth combo strikes, sequential attacks with jump action, etc in the same world. Enjoy hunting monsters and quests in the MMO field (multiplayer field), or the Dungeon in the MO Field (Played by parties or by solo), the PvP (Player versus player)",
                "Come explore a world under battle over the vital resource: Mana Crystals! Summon over 400 different types of monsters to compete for victory in the Sky Arena!",
                "In the year 2841, a new chapter in the story of humanity is beginning as we expand to the furthest stars in the universe. In a sci-fi landscape of mystery, intrigue, and opportunity, you'll take the reigns as Commander of a galactic outpost vying for power. It won't be easy though, you'll need to marshal all your forces and employ a variety of strategies to repel those who wish to eradicate you. Make no mistake: the threat of Space Pirates, enemy outposts, aliens, and the unknown looms before us. Your legend is waiting to be written, Commander.",
                "Evade a relentless police force while you clash with street racers. Race and chase hot cars like the SRT Viper GTS, Porsche 911 Carrera S, Hummer H1 Alpha, and many more. Feel the intensity of no-brakes-allowed street racing with realistic full-car damage for the first time on mobile.",
                "Drive your way through a zombie apocalypse! Are you ready to drive for your life? The hit online game series that has enjoyed OVER 200 MILLION PLAYS has been revamped and re-engineered for your mobile and tablet, bigger and better than ever before!",
                "With more than 6 millions of fan players worldwide, Real Drift Car Racing is the most realistic 3D drift racing simulation on mobile devices, and yet easy to control and fun to play thanks to an innovative drift helper.",
                "Downhill mountain bike racing like never before. Race down beautiful trails, smashing over rocks and roots, boosting huge jumps, scoring insane trick combos, unlocking better bikes and gear for bragging rights as the King of the Mountain! The best mobile bike game, Bike Mayhem Extreme Mountain Racing!",
                "Reckless Racing is back with dirtier racetracks, more epic power slides, eye-popping graphics and the largest selection of cars and trucks to date. Play the career mode loaded with 60 events in 9 different seasons and the Arcade mode featuring 24 challenges, or compete on the online leaderboards in Single Event. Reckless Racing 3 has the most detailed physics and complex graphics so far, giving you the smoothest racing experience ever.",
                "Lightning McQueen and Mater are hosting a Radiator Springs car racing EXTRAVAGANZA, and they need some speed! Do you have the drive to play? Race fast and free as Cars characters with nitro-charged arcade racing! Then build your own 3D Radiator Springs, home of Lightning and his buddies. Watch it go from a humble town to a thriving city!",
                "CHOOSE YOUR LEVEL AND LOOK Play through 3 levels of difficulty and save games in progress. Also customize the number of players, the game rules, and even the game environment. Enjoy MONOPOLY in the tradition of the beloved, best-selling board game! Be the first to know! Get inside EA info on great deals, plus the latest game updates, tips & more…",
                "Ticket to Ride® for Android is a cross-country train adventure playable online, in which you will collect and play train cards to claim railway routes connecting cities listed on Destination Tickets you will receive at the start of each game. The longer your routes, the more points you'll earn. But be careful not to find yourself blocked off by your opponents, as each Destination ticket not fulfilled will cost you dearly",








            );
            $rand_project = mt_rand(0,count($project_names_arr) - 1);
            // echo "pr - name : ".count($project_names_arr)."<br >";
            // echo "pr - des : ".count($project_description_arr)."<br >";exit;
            $project_logo = array(
                '2f9b7e04ca5ba2fdaaa1f7dee7fccf6b.png',
                '3efff19101fc62fa355352a116fd1453.png',
                '5db8b4366483dbf700635d16e6a0b8f1.png',
                '9ef518c8e67ac2ad4e63747a90fd9d5e.png',
                '81dc9bdb52d04dc20036dbd8313ed055.png',
                '202cb962ac59075b964b07152d234b70.png',
                '287d1e39fc33fc519b8d2c60a8056eb7.png',
                '512c872410f5a76c4397b08c99098b42.png',
                '827ccb0eea8a706c4c34a16891f84e7b.png',
                '9591b0fc3c821ab67f1ad1de3c5bb882.png',
                'c20ad4d76fe97759aa27a0c99bff6710.png',
                'c55a1944c365e76bd9817a02d056e50c.png',
                'cd374e844554edebd96dc46ccdbed845.png',
                'ce4e635c39f24a78d52e5f37596af673.png',
                'd4277b859d6cd133b80f3b603314c467.png',
                'e10adc3949ba59abbe56e057f20f883e.png',
                'fe6d1fed11fa60277fb6a2f73efb8be2.png',
                '5f1aaefc8aa9cfe81c1a1aeb4d3db161.png',
                '9981f73dbd06ad877c2b5b1f9e3aaf13.png',
                'b2e5f247cc71d6671ffa8bc5abae98d8.png',
                'f68c49aabf2e20bcd053cd3618cc21b7.png'
            );
            $projects_status = array('0','1','2','3','4','5');
            $dataInsert2 = array(
                'projects.project_name'         => $project_names_arr[$rand_project],
                'projects.project_status'       => $projects_status[mt_rand(0,sizeof($projects_status) - 1)],
                'projects.description'          => $project_description_arr[$rand_project],
                'projects.project_categories'   => $categories_rand1,
                'projects.views'                => $view,
                'projects.budget_min'           => $bget_min0[$rand],
                'projects.budget_max'           => $bget_max1[$rand],
                'projects.group_ids'            => $insert_groupids,
                'projects.group_id'             => $group_id[$rand1],
                'projects.creator_id'           => $client_id[mt_rand(0,sizeof($client_id) - 1)],
                'projects.programmer_id'        => $freelancer_id[mt_rand(0,sizeof($freelancer_id) - 1)],
                'projects.flag'                 => 1,
                'projects.attachment_avatar'    => $project_logo[mt_rand(0,sizeof($project_logo) -1)],
                'projects.created'              => time(),
                'projects.enddate'              => time() + 604800017
            );
            $show[] = $this->user_model->createProjectRandom($dataInsert2);
        }/* --- end for --- */
        echo "<pre>";
        print_r($show);
        echo "</pre>";
    }
    function insertUsersRandomIntoDBUpdate(){
         $this->load->helper('users');
        /* ----- insert user vào bảng user ----- */
        $insert_id = array();
        $user_categories_id = array();
        $ten_nguoi = "Agnes, Alice, Angela, Ann, Anne, Barbara, Caroline, Catherine, Christina, Cindy, Claudia, Dorothy, Elizabeth, Evelyn, Emily, Florence, Florence, Grace, Helen, Hilary, Irene, Isabel, Jane, Janet, Jessica , Juliet, June, Katherine, Kitty, Laura, Linda, Madeleine, Margaret, Maria, Marilyn, Mary, Monica, Nancy, Natasha, Rose, Ruby, Teresa, Victoria, Vera, Violet,Abraham, Adam, Albert, Alexander, Andrew, Allan, Arthur, Benjamin, Bernard, Bill, Bob, Charlie, Christopher, Clark, Clifford, Colin, Craig, Daniel, David, Dennis, Douglas, Edmund, Felix, Ferdinand, Francis, Gary, George, Gilbert, Gordon, Henry, Howard, Hugh, Humphrey, Ian, Isaac, Ivan, Jack, James, Jimmy, John, Jonathan, Joseph, Laurence,  Luis, Leonard, Martin, Matthew, Michael, Neil, Murray, Oliver, Patrick, Oscar, Owen, Richard, Peter, Robert, Rodney, Ronald, Samuel, Sebastian, Stanley, Thomas, Tom, Victor, Warren, William";
        $ten_nguoi_arr = explode(',', $ten_nguoi);
        $expand_email = array('gmail','yahoo','applancer','florist','cab','hotmail','blog','consultant','asia','accountant','contractor','comic','iname','computer4u','teppi','technology','today','dance','solution','academy','repair','solar');
        $extensions_email = array('com','net','org','biz','gov','co','club','sport','info','edu');
        shuffle($extensions_email);
        $users_logo = array(
            '0cb9f131263f4076cfb4cd3b6479f8a2.png',
            '2d1fcbab33cd2ebd2e27205ce63c64d4.png',
            '4ad4ce782f0c83e1721b15c442e1005b.png',
            '4cee03b0573c7293cd23932e4b77b04b.png',
            '8b9617bbf2b028e2a135c47324e4b771.png',
            '9f00acb473e5c1f253699ca32ea452bd.png',
            '29c9a2a30987d539a3d28a20127c631f.png',
            '039e0552f43b9f92cc7c3977001e6bb9.png',
            '77d9973e6402edf8bc70b6b149504a81.png',
            '432b07c1194d9b2df0f5c0368e2aa92d.png',
            '7800d764282104fe1668635e198b81ac.png',
            '8083ab9f29fdb69cbddec3b50166044d.png',
            '3857875222e4bee0a2c6c752543ff10a.png',
            'a482cf4c6bae1b259244b00734a7f46e.png',
            'a296062ac7c6b55a8e07a78510c03dc2.png',
            'bb396b212607506dd4488c7439116832.png',
            'c17ab05c34951b6a2a17d4a36bccf1a7.png',
            'cc18bfffd0eedeca0117dab0e4f2eba6.png',
            'd7e5a93fee6d4fb24af55d4f2823a7d3.png',
            'da5851aec69767bf7842aac5bc09d676.png',
            'ea4cbb1aa9c1deba40685d73b12e0fdd.png',
            'f01a43d0b61ce3afc58794b6c33b281c.png',
            'e490ea7120eaf67ff353936086bf6235.png',
        );
        $description_arr = array(
            "My self Rahul Jaicker. I'm from bihar. Coming to my qualification I'm studying 2 B-Tech in mechanical from S. C. R engg college guntur. It's university JNTU kakinada. I have completed I.Sc from R. D&D. J college munger and I have done my schooling in zilla high school munger.",
            "I have recently completed my B-Tech in Electrical and Electronics Engineering at VEMU College of Engineering and Technology, Chittoor. +2 at Narayana Jr College and SSC at Vijaya English Medium High School, Chittoor.",
            "I love playing Chess and Cricket, I like photography a lot. My strengths are quick learner, can excel both as a team and as an individual, self driven and focussed. ",
            "Coming to my family, we totally 5 in number including me. My father is working in transportation department, my mother is a Tailor cum homemaker, I have 2 siblings an elder sister doing job in medical department as staff nurse and younger brother pursuing B-Tech in ECE stream, that's all about my family.",
            "About my weakness I'm not comfortable until I finish my work & I believe others easily. My hobby is in free time I do internet surfing, play chess & reading news. My short term goal is I want to complete gate.",
            "I have Completed my 10th & 10th+2 From KOTA Rajasthan. Currently Pursuing as the Student B-Tech (4/4) Civil Engineering At NIT Warangal. With 1st Class Equivalent CGPA.",
            "My Family have Six Member in Which my Parent & two my Elder Brother & one my Younger Sister. My Father Is Businessmen & My Mother Is HM. Both of My Elder Brother is doing their self Business & My Sister Is doing his Graduation. That is my Famaly Detail.",
            "My Strength is Self motivated Punctual diligence concentrate only on GOAL till it will not achieve. My weakness is I did not work under Pressure.",
            "I'm Agnes Sujhithra, doing BE computer science. Being non-graduates my parents worked hard and supported my education so much which made me diligent and inspired me to be the topper in my school. I am quite interested in solving mathematical problems. I always wish to be a perfectionist. I am waiting to get exposed in a working environment where I can utilize my skills and develop my knowledge.",
            "I have an ability to adapt myself to the surrounding and I want to enjoy my work. My short term goal is to attain a job which gives me a practical learning life of engineering and long term goal is to become an expert in computer developments.",
            "Actually sir I am Rohit dhama. I am live in meerut. I have completed MCA. I have 3+ years experience in software development on dot net technology. I have 4 member in my family included me.",
            "I form shigli belongs to Gadag dist. I have completed BBA at S J F Govt first grade college shirahatti.",
            "Come to my family consisted six members my father is an agriculture my mother is home worker I have one younger brother and sister and I have one elder sister. My hobbies are listing music and plantation.",
            "My father is farmer, my mother is home maker, I have 3 elder sisters. About my educational qualification, I did my schooling in st mary, s hr sec school in Dindigul.",
            "Now I'm doing BE. , civil engineering in ssm institute of engineering and technology with 65%. My strength is ability to handle the pressure at any situation. My weakness is cricket. My goal is to placed in a core company.",
            "I have Bachelor Degree and now student of MBA. My Father is a retired Army Soldier and my mother is a housewife. I have 2 brothers and 2 sisters. I have great patience level and forgive most of people.",
            "I like to play cricket. Like Inzamam and wasim akram. I want to be a transformational leader and like to give everything I have to humanity.",
            "I belongs to a family of five member including me. I achieved a pgd-ppt degree from cipet balasore and also graduated from nayagarh autonomous college chemistry hons. With 61%. I have a little experience in plastic industry. That practiced during training. But I have skill all about plastics.",
            "My short term goal is to a job. In your company. My long term goal I want to build up a new company. . And sit in your position in my company. My hobbies hard working.",
            "I emotional while I see a hapless person. At last thanks for give me some valuable time. Thank you.",
            "Hi This is Ratnesh kumar singh. I'm from Varanasi in Uttar Pradesh. Five members in my family including me my father do plating and my mother is housewife and I have two elder sister both are married.",
            "I have passed out. SSC exam with 55.5% mark from UP Board in 2009 and I have passed out HSC exam with 70.4% from UP Board in 2011. And now I completed BCA from institute of computer science and technology affiliated with Mahatma Gandhi Kashi VidhyaPith in short M. G. K. V. P. I am also interested in programming with C, C++ and HTML also.",
            "My strength is to do hard work for achieve our decided goal. My weakness is believe on everybody. My hobby is planting.",
            "My highest qualification is B-Tech, graduated from JNTU Hyderabad university with 67%. Coming to my family there are 5 members including me, my father is a police, mother is housewife & I have 2 younger brothers. My strengths are, I am self motivated and target oriented person.",
            "As a fresher I don't have work experience but I have skills related to software. My goal is to get a entry level position in IT. And that's all about me in a brief.",
            "My strengths are positive attitude, good team worker. My weakness is, I feel uncomfortable until my work done. My short term goal is to get challenging position in your company. My long term goal is to reach the highest position in my company.",
            "I have done my schooling from St.Paul's School in Rampur. I completed my 10th with 84% and 12th with 80%. I have completed my graduation in statistics from Ram Lal Anand College Delhi University with 75%. My hobbies are watching movies and sports, playing table tennis.",
            "I am a quick learner and punctual and also I can work in unfavorable situations. I like to explore new places and so I can work at any location. My weakness is I am a bit emotional and easily believe in strangers.",
            "My short term goal is to get a job in a reputed company like yours where I can learn tools and skills of analysis and develop my concepts and knowledge. I am a kind of a person who believe that if make a goal for today and dedicate myself on it I will be in a better place tomorrow so I don't make long term goals. Honestly this all about me.",
            "I am Mohana kannan from Thirukoikur doing my final year BE in Sri Krishna college of Technology with 77%. I have completed my SSLC with 86% in Sri Gnanananda matriculation higher secondary school. After that I have completed my +2 with 82% in Sri Gnanananda matriculation higher secondary school.",
            "My hobbies are writing poems in Tamil, hearing songs and riding bicycles. My short time goal is to get placed in your company and my long time goal is to a role model for my juniors. I am the chairman of Sri krishna college of technology's tamil language club. My strength is self motivated and a hard worker. My weaknesses is I trust everyone easily.",
            "My technical skills: P.G.D.C.A and speed typing and HTML Photoshop. Regarding to my family background: we are 5 numbers include me. My father is a labour my mother is a labour. I have 2 siblings. My elder is married. Younger brother is studying his B.A.",

            );
        for ($i=0; $i < 10; $i++){
            $role_id = mt_rand(1,2);
            $username = trim($ten_nguoi_arr[mt_rand(0,sizeof($ten_nguoi_arr) -1)]);
            $email = $username."@".$expand_email[mt_rand(0,sizeof($expand_email) -1)].".".$extensions_email[mt_rand(0,sizeof($extensions_email) -1)];
            $city = mt_rand(1,63);
            $user_rating = mt_rand(0,5);
            $num_reviews = mt_rand(1,100);
            $password = '25f9e794323b453885f5181f1b624d0b';
            $dataInsert = array(
                'users.user_name'     => $username,
                'users.password'      => $password,
                'users.role_id'       => $role_id,
                'users.email'         => $email,
                'users.city'          => $city,
                'users.user_rating'   => $user_rating,
                'users.num_reviews'   => $num_reviews,
                'users.user_status'   => 1,
                'users.logo'          => $users_logo[mt_rand(0,sizeof($users_logo) -1)],
                'users.profile_desc'  => $description_arr[mt_rand(0,sizeof($description_arr) - 1)]
            );
                $insert_id[] = $this->user_model->createUserRandom($dataInsert);
        }/* end */

        /* ----- insert vào bảng user_categories ----- */
        for ($j=0; $j < count($insert_id) ; $j++) {
            $cate_rand = array();
            for($i=0; $i<= 2; $i++){
                $cate_rand[] = mt_rand(12,64);
            }
            $categories_rand = implode(',',$cate_rand);
            $dataInsert1 = array(
                'user_id'           => $insert_id[$j],
                'user_categories'   => $categories_rand,
            );
            $user_categories_id[] = $this->user_model->createCategoriesRandom($dataInsert1);

        } /* end */

    } /* --- end function --- */


    function testExcelFile(){
        $filename = APPPATH.'excel/demo.xls';
        require_once APPPATH.'excel/excel_reader2.php';
        $data = new Spreadsheet_Excel_Reader($filename,false,'utf-8');// khoi tao doi tuong doc file excel
        $rowsnum = $data->rowcount($sheet_index=0); // lay so hang cua sheet
        $colsnum =  $data->colcount($sheet_index=0); // lay so cot cua sheet
        echo $rowsnum-1;
        for ($i=2;$i<=$rowsnum;$i++) // doc tu hang so 2 vi hang 1 la tieu de roi!
            echo "<br>".$data->val($i,1)." , ".$data->val($i,2);

    }

    function loginFacebook(){
        //echo $this->input->post('email',TRUE);exit;
        if($this->input->post('email',TRUE)) {
            $conditions = array('email' => $this->input->post('email',TRUE));
            //$fields = array('users.email', 'users.id as id', 'roles.role_name','roles.role_id');
            $user = $this->user_model->getUsers($conditions);
            if ($user->num_rows() > 0) {
                $row = $user->row();
                // update the last activity in the users table
                $updateData = array();
                $updateData['last_activity'] = get_est_time();

                // update process for users table
                $this->user_model->updateUser(array('id' => $row->id), $updateData);

                $this->auth_model->setUserSession($row);
                echo json_encode(array('status' => 'success','role' => $row->role_id));exit;
            } else {
                echo json_encode(array('status' => 'error'));exit;
            }
        }
    }


   

    function showPageCropPhoto(){
        $this->load->helper(array('form', 'url','file'));
        //Load Library Validation
        $this->load->library('upload');
        $this->load->library('images');
        $this->load->library('Image_moo');
        $this->outputData['upload_path']        = $upload_path          = "files/logos/" ;
        $this->outputData['destination_thumbs'] = $destination_thumbs   = "files/thumbs_logos/" ;

        $this->outputData['large_photo_exists'] = $this->outputData['thumb_photo_exists'] = $this->outputData['error'] = NULL ;
        $this->outputData['thumb_width']        = "200";
        $this->outputData['thumb_height']       = "200";
        
        if (!empty($_POST['upload'])) {
           $file = upload_image($_FILES,'logos','image');
            if (isset($file['file_name']) == TRUE) {
                $this->outputData['img']     = $file;
                $this->outputData['large_photo_exists']  = "<img src=\"".base_url() . $upload_path.$file['file_name']."\" alt=\"Large Image\"/>";
            }else{
                $this->outputData['error_upload'] = $file;
            }
        }
        elseif (!empty($_POST['upload_thumbnail'])) {
            $x1 = $this->input->post('x1',TRUE) ;
            $y1 = $this->input->post('y1',TRUE) ;
            $x2 = $this->input->post('x2',TRUE) ;
            $y2 = $this->input->post('y2',TRUE) ;
            $w  = $this->input->post('w',TRUE) ;
            $h  = $this->input->post('h',TRUE) ;

            $file_name = $this->input->post('file_name',TRUE) ;
            if ($file_name) {
                $this->image_moo
                    ->load($upload_path . $file_name)
                    ->crop($x1,$y1,$x2,$y2)
                    ->save($destination_thumbs . $file_name) ;

                if ($this->image_moo->errors) {
                    $this->outputData['error_upload'] = $this->image_moo->display_errors() ;
                }
                else {
                    $updateData['logo']    = $file_name;
                    $updateKey = array('id' => $this->loggedInUser->id);
                    $this->user_model->updateUser($updateKey, $updateData);
                    redirect('buyer/editProfileUpdate');
                }
            }

        }
        
        $this->load->view('buyer/modalShowAddPhoto',$this->outputData) ;
    }

    function addReview(){
        //print_r($_POST);exit;
        if(isset($this->loggedInUser->id) == TRUE) {
            if ($this->input->post('project_id', TRUE)) {
                $insertReview['project_id'] = $this->input->post('project_id', TRUE);
                if($this->loggedInUser->role_name == 'programmer') {
                    $insertReview['review_type'] = 2;
                    $insertReview['buyer_id'] = $this->input->post('user_id',TRUE);
                    $insertReview['provider_id'] = $this->loggedInUser->id;
                }elseif($this->loggedInUser->role_name = 'buyer'){
                    $insertReview['review_type'] = 1;
                    $insertReview['buyer_id'] = $this->loggedInUser->id;
                    $insertReview['provider_id'] = $this->input->post('user_id',TRUE);
                }
                $insertReview['project_review'] = $this->input->post('project_review',TRUE);
                $insertReview['info_review'] = $this->input->post('info_review',TRUE);
                $insertReview['expertise_review'] = $this->input->post('expertise_review',TRUE);
                $insertReview['hire_review'] = $this->input->post('hire_review',TRUE);
                $insertReview['professional_review'] = $this->input->post('professional_review',TRUE);
                $insertReview['comments'] = $this->input->post('comments',TRUE);
                $insertReview['percent_review'] = $this->input->post('percent_review',TRUE);
                $insertReview['budget_review'] = $this->input->post('budget_review',TRUE);
                $insertReview['time_review']    = $this->input->post('time_review',TRUE);
                $insertReview['review_time'] = time();

                $user_info = $this->user_model->getUsers(array('users.id' => $this->input->post('user_id',TRUE)),array('users.tot_rating','users.user_rating','users.num_reviews'))->row();

                $insertUserReview['tot_rating'] = $user_info->tot_rating + $this->input->post('rating',TRUE);
                $insertUserReview['user_rating'] = $user_info->user_rating + 1;
                $insertUserReview['num_reviews'] = $user_info->num_reviews + 1;

                $this->user_model->updateUser(array('users.id' => $this->input->post('user_id',TRUE)),$insertUserReview);

                $this->common_model->insertData('reviews',$insertReview);
                echo json_encode(array('status' => 'success'));exit;
            }else{
                echo json_encode(array('status' => 'error'));exit;
            }
        }
    }

    function croppic(){
        $this->load->view('buyer/croppic');
    }
    function img_save_to_file(){
        $imagePath = 'files/logos/';

        $allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG");
        $temp = explode(".", $_FILES["img"]["name"]);
        $extension = end($temp);

        if( in_array($extension, $allowedExts)){
            if ($_FILES["img"]["error"] > 0){
                 $response = array(
                    "status" => 'error',
                    "message" => 'ERROR Return Code: '. $_FILES["img"]["error"],
                );
                echo "Return Code: " . $_FILES["img"]["error"] . "<br>";
            }
            else{                
                $filename = $_FILES["img"]["tmp_name"];
                list($width, $height) = getimagesize( $filename );
                move_uploaded_file($filename,  $imagePath . $_FILES["img"]["name"]);
                // $updateData['logo']    = $_FILES["img"]["name"];
                // $updateKey = array('id' => $this->loggedInUser->id);
                // $this->user_model->updateUser($updateKey, $updateData);
                $response = array(
                    "status" => 'success',
                    "url" => base_url().$imagePath.$_FILES["img"]["name"],
                    "width" => $width,
                    "height" => $height
                );
            }
        }else{
            $response = array(
                "status" => 'error',
                "message" => 'something went wrong',
            );
        }
            print json_encode($response);
    }

    function img_crop_to_file(){   
        $imgUrl = $_POST['imgUrl'];
        $imgInitW = $_POST['imgInitW'];
        $imgInitH = $_POST['imgInitH'];
        $imgW = $_POST['imgW'];
        $imgH = $_POST['imgH'];
        $imgY1 = $_POST['imgY1'];
        $imgX1 = $_POST['imgX1'];
        $cropW = $_POST['cropW'];
        $cropH = $_POST['cropH'];

        $jpeg_quality = 100;
        $name_rand = md5(time());
        $output_filename = "files/thumbs_logos/".$name_rand;

        $what = getimagesize($imgUrl);
        switch(strtolower($what['mime']))
        {
            case 'image/png':
                $img_r = imagecreatefrompng($imgUrl);
                $source_image = imagecreatefrompng($imgUrl);
                $type = '.png';
                break;
            case 'image/jpeg':
                $img_r = imagecreatefromjpeg($imgUrl);
                $source_image = imagecreatefromjpeg($imgUrl);
                $type = '.jpeg';
                break;
            case 'image/gif':
                $img_r = imagecreatefromgif($imgUrl);
                $source_image = imagecreatefromgif($imgUrl);
                $type = '.gif';
                break;
            default: die('image type not supported');
        }
            
            $resizedImage = imagecreatetruecolor($imgW, $imgH);
            imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW, 
                        $imgH, $imgInitW, $imgInitH);   
            
            
            $dest_image = imagecreatetruecolor($cropW, $cropH);
            imagecopyresampled($dest_image, $resizedImage, 0, 0, $imgX1, $imgY1, $cropW, 
                        $cropH, $cropW, $cropH);    


            imagejpeg($dest_image, $output_filename.$type, $jpeg_quality);
            $updateData['logo']    = $name_rand.$type;
            $updateKey = array('id' => $this->loggedInUser->id);
            $this->user_model->updateUser($updateKey, $updateData);
            $response = array(
                    "status" => 'success',
                    "url" => base_url().$output_filename.$type 
                );
             print json_encode($response);

    }


    //---------------------------------------------------------------------

} //End  Buyer Class

/* End of file Buyer.php */
/* Location: ./app/controllers/Buyer.php */
?>
